package com.bytesw.bytebot.service;

import com.bytesw.bytebot.bean.AirportBean;
import com.bytesw.bytebot.model.Airport;
import com.bytesw.bytebot.repository.AirportRepository;
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 AirportService extends XDFService<Airport, AirportBean, Long> {

    @Autowired
    private AirportRepository airportRepository;

    protected AirportService(AirportRepository repository) {
        super(repository);
    }

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

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

    @Override
    public AirportBean create(AirportBean bean) {
        if (this.airportRepository.existsById(bean.getId())) {
            throw new AlreadyExistsException();
        }
        Airport model = new Airport();
        model = this.airportRepository.save(this.toModel(model, bean));
        return this.toBean(model);
    }

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

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