package com.bytesw.bytebot.service;

import com.bytesw.bytebot.bean.CostBean;
import com.bytesw.bytebot.bean.LegBean;
import com.bytesw.bytebot.model.Airport;
import com.bytesw.bytebot.model.Cost;
import com.bytesw.bytebot.model.Flight;
import com.bytesw.bytebot.model.Leg;
import com.bytesw.bytebot.repository.CostRepository;
import com.bytesw.bytebot.repository.FlightRepository;
import com.bytesw.xdf.exception.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class CostService {
    @Autowired
    private CostRepository costRepository;

    @Autowired
    private FlightRepository flightRepository;

    public void create(CostBean bean) {
        Optional<Flight> flight = this.flightRepository.findById(bean.getFlightId());
        if (!flight.isPresent()) {
            throw new NotFoundException();
        }
        Cost model = new Cost();
        model.setFlight(flight.get());
        model.setAirline(bean.getAirline());
        model.setAmount(bean.getAmount());
        model.setToDate(bean.getToDate());
        model.setFromDate(bean.getFromDate());
        this.costRepository.save(model);
    }

    public void update(CostBean bean, Long id) {
        Optional<Cost> found = this.costRepository.findById(id);
        Optional<Flight> flight = this.flightRepository.findById(bean.getFlightId());
        if (!found.isPresent()) {
            throw new NotFoundException();
        }
        if (!flight.isPresent()) {
            throw new NotFoundException();
        }
        Cost model = found.get();
        model.setFlight(flight.get());
        model.setAirline(bean.getAirline());
        model.setAmount(bean.getAmount());
        model.setToDate(bean.getToDate());
        model.setFromDate(bean.getFromDate());
        this.costRepository.save(model);
    }

    public List<Cost> getCost(Long id) {
        List<Cost> found = costRepository.findAllByFlight_Id(id);
        if (found.isEmpty()) {
            throw new NotFoundException();
        }
        return found;
    }
}
