[ce6ad22] | 1 | package parkup.services;
|
---|
| 2 |
|
---|
| 3 | import java.util.List;
|
---|
| 4 | import java.util.Optional;
|
---|
| 5 | import org.springframework.beans.factory.annotation.Autowired;
|
---|
[3753356] | 6 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
---|
[ce6ad22] | 7 | import org.springframework.stereotype.Service;
|
---|
| 8 | import parkup.entities.Guest;
|
---|
| 9 | import parkup.repositories.GuestRepository;
|
---|
| 10 |
|
---|
| 11 | @Service
|
---|
| 12 | public class GuestService {
|
---|
| 13 | private final GuestRepository guestRepository;
|
---|
[3753356] | 14 | private final BCryptPasswordEncoder passwordEncoder;
|
---|
[ce6ad22] | 15 |
|
---|
| 16 | @Autowired
|
---|
[3753356] | 17 | public GuestService(GuestRepository guestRepository, BCryptPasswordEncoder passwordEncoder) {
|
---|
[ce6ad22] | 18 | this.guestRepository = guestRepository;
|
---|
[3753356] | 19 | this.passwordEncoder = passwordEncoder;
|
---|
[ce6ad22] | 20 | }
|
---|
| 21 |
|
---|
| 22 | public List<Guest> getGuests() {
|
---|
| 23 | return this.guestRepository.findAll();
|
---|
| 24 | }
|
---|
| 25 |
|
---|
| 26 | public Guest findById(int guestId) {
|
---|
| 27 | Optional<Guest> guest = Optional.ofNullable(this.guestRepository.findByGuestId(guestId));
|
---|
| 28 | return guest.orElse(null);
|
---|
| 29 | }
|
---|
| 30 |
|
---|
| 31 | public void addGuest(Guest guest) {
|
---|
| 32 | Optional<Guest> guestOpt = this.guestRepository.findGuestByEmail(guest.getEmail());
|
---|
| 33 | if (guestOpt.isPresent()) {
|
---|
| 34 | throw new IllegalStateException("Email already taken, try adding a guest with a different valid email address");
|
---|
| 35 | } else {
|
---|
[3753356] | 36 | // guest.setPassword(passwordEncoder.encode(Math.random()));
|
---|
[ce6ad22] | 37 | this.guestRepository.save(guest);
|
---|
| 38 | }
|
---|
| 39 | }
|
---|
| 40 |
|
---|
| 41 | public void deleteGuest(int guestId) {
|
---|
| 42 | Optional<Guest> guest = Optional.ofNullable(this.guestRepository.findByGuestId(guestId));
|
---|
| 43 | if (guest.isPresent()) {
|
---|
| 44 | this.guestRepository.deleteByGuestId(guestId);
|
---|
| 45 | } else {
|
---|
| 46 | throw new IllegalStateException("Guest doesn't exist, therefore can't be deleted");
|
---|
| 47 | }
|
---|
| 48 | }
|
---|
| 49 | }
|
---|