package com.bytesw.bytebot.service;

import com.bytesw.bytebot.bean.PassengerBean;
import com.bytesw.bytebot.model.Passenger;
import com.bytesw.bytebot.repository.PassengerRepository;
import com.bytesw.xdf.exception.AlreadyExistsException;
import com.bytesw.xdf.exception.NotFoundException;
import com.bytesw.xdf.service.XDFService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
@Transactional
public class PassengerService extends XDFService<Passenger, PassengerBean, Long> {

    @Autowired
    private PassengerRepository passengerRepository;

    protected PassengerService(PassengerRepository repository) {
        super(repository);
    }


    @Override
    protected Passenger toModel(Passenger model, PassengerBean bean) {
        if (model == null) {
            model = new Passenger();
        }
        BeanUtils.copyProperties(bean, model);
        return model;
    }

    @Override
    protected PassengerBean toBean(Passenger model) {
        PassengerBean bean = new PassengerBean();
        BeanUtils.copyProperties(model, bean);
        return bean;
    }

    @Override
    public PassengerBean create(PassengerBean bean) {
        Passenger model = new Passenger();
        model = this.passengerRepository.save(this.toModel(model, bean));
        return this.toBean(model);
    }

    @Override
    public PassengerBean update(PassengerBean bean, Long id) {
        Optional<Passenger> found = this.passengerRepository.findById(id);
        if (!found.isPresent()) {
            throw new NotFoundException();
        }
        Passenger model = this.toModel(found.get(), bean);
        BeanUtils.copyProperties(model, found.get());
        model = this.passengerRepository.save(found.get());
        return this.toBean(model);
    }

    @Override
    public void delete(Long id) {
        Optional<Passenger> found = this.passengerRepository.findById(id);
        if (!found.isPresent()) {
            throw new NotFoundException();
        }
        this.passengerRepository.delete(found.get());
    }

}
