Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

package com.cabbooking.customerservice.

service;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cabbooking.customerservice.entity.Client;
import com.cabbooking.customerservice.exception.InvalidIdException;
import com.cabbooking.customerservice.exception.NullDataException;
import com.cabbooking.customerservice.repository.AddressRepository;
import com.cabbooking.customerservice.repository.ClientRepository;

@Service
public class ClientServiceImpl implements ClientService {

@Autowired
private ClientRepository clientRepository;

@Autowired
private AddressRepository addressRepository;

@Override
public Client saveClient(Client client) {
return clientRepository.save(client);
}

@Override
public Client findClient(int clientId) throws InvalidIdException {
Optional<Client> optionalClient = clientRepository.findById(clientId);
if (optionalClient.isEmpty()) {
throw new InvalidIdException("Client not found with ID: " +
clientId);
}
return optionalClient.get();
}

@Override
public Client updateClient(Client client) throws InvalidIdException {
Optional<Client> optionalClient =
clientRepository.findById(client.getClientId());
if (optionalClient.isEmpty()) {
throw new InvalidIdException("No client found with ID: " +
client.getClientId());
}
clientRepository.save(client);
return client;
}

@Override
public String deleteClient(int clientId) throws InvalidIdException {
Client client = clientRepository.findById(clientId)
.orElseThrow(() -> new InvalidIdException("Client with ID "
+ clientId + " does not exist."));
addressRepository.delete(client.getAddress());
clientRepository.delete(client);
return "Deleted successfully.";
}
@Override
public List<Client> getAllClients() throws NullDataException {
List<Client> clients = clientRepository.findAll();
if (clients.isEmpty()) {
throw new NullDataException("No data available.");
}
return clients;
}

@Override
public Client validateClient(String email, String password) throws
InvalidIdException {
List<Client> clients = clientRepository.findAll();
for (Client client : clients) {
if (client.getEmail().equals(email) &&
client.getPassword().equals(password)) {
return client;
}
}
throw new InvalidIdException("Invalid email or password.");
}

You might also like