1 | package mk.ukim.finki.eglas.services.Impl;
|
---|
2 |
|
---|
3 | import jakarta.transaction.Transactional;
|
---|
4 | import mk.ukim.finki.eglas.model.Coalition;
|
---|
5 | import mk.ukim.finki.eglas.model.ElectionRealization;
|
---|
6 | import mk.ukim.finki.eglas.repository.CoalitionRepository;
|
---|
7 | import mk.ukim.finki.eglas.services.CoalitionService;
|
---|
8 | import mk.ukim.finki.eglas.services.ElectionRealizationService;
|
---|
9 | import mk.ukim.finki.eglas.services.PartyService;
|
---|
10 | import org.springframework.data.repository.query.Param;
|
---|
11 | import org.springframework.stereotype.Service;
|
---|
12 |
|
---|
13 | import java.util.ArrayList;
|
---|
14 | import java.util.List;
|
---|
15 |
|
---|
16 | @Service
|
---|
17 | public class CoalitionServiceImpl implements CoalitionService {
|
---|
18 |
|
---|
19 | private final CoalitionRepository coalitionRepository;
|
---|
20 | private final ElectionRealizationService electionRealizationService;
|
---|
21 | private final PartyService partyService;
|
---|
22 |
|
---|
23 | CoalitionServiceImpl(CoalitionRepository coalitionRepository,
|
---|
24 | ElectionRealizationService electionRealizationService,
|
---|
25 | PartyService partyService){
|
---|
26 | this.coalitionRepository = coalitionRepository;
|
---|
27 | this.electionRealizationService = electionRealizationService;
|
---|
28 | this.partyService = partyService;
|
---|
29 | }
|
---|
30 |
|
---|
31 |
|
---|
32 | @Override
|
---|
33 | public Coalition findById(Long id) {
|
---|
34 | return coalitionRepository.findById(id).orElseThrow(() -> new RuntimeException("No coalition found"));
|
---|
35 | }
|
---|
36 |
|
---|
37 | @Override
|
---|
38 | public List<Coalition> findAll() {
|
---|
39 | return coalitionRepository.findAll();
|
---|
40 | }
|
---|
41 |
|
---|
42 | @Override
|
---|
43 | public void addPartyToCoalition(Long coalitionId, Long partyId) {
|
---|
44 | Coalition coalition = findById(coalitionId);
|
---|
45 | coalition.getParties().add(partyService.findById(partyId));
|
---|
46 | coalitionRepository.save(coalition);
|
---|
47 | }
|
---|
48 |
|
---|
49 | @Transactional
|
---|
50 | @Override
|
---|
51 | public Coalition update(Long id, String name, String motto, Long electionRealization, List<Long> partiesId) {
|
---|
52 | Coalition coalition;
|
---|
53 | if (id != null){
|
---|
54 | coalition = findById(id);
|
---|
55 | }else {
|
---|
56 | coalition = new Coalition();
|
---|
57 | }
|
---|
58 | coalition.setName(name);
|
---|
59 | coalition.setMotto(motto);
|
---|
60 | coalition.setElectionRealization(electionRealizationService.findById(electionRealization));
|
---|
61 | coalitionRepository.save(coalition);
|
---|
62 | partiesId.forEach(partyId -> addPartyToCoalition(coalition.getId(), partyId));
|
---|
63 | return coalition;
|
---|
64 | }
|
---|
65 |
|
---|
66 | @Override
|
---|
67 | public void delete(Long id) {
|
---|
68 | coalitionRepository.delete(findById(id));
|
---|
69 | }
|
---|
70 | }
|
---|