package TS;

import RDG.AircraftType;
import RDG.Flight;
import RDG.SeatCount;
import java.sql.SQLException;

/**
 *
 * @author Marcel
 */
public class AircraftChangeTS {
    /**
     * Changes aircraft on flight.
     * isolation level: serializable
     * - check if can replace aircraft
     * - change booked seats
     * - change aircraft type
     * @param flight_id on which flight change
     * @param new_aircraft_id to which aircraft.
     * @throws SQLException
     * @throws Exception
     * @return Boolean if everything went right 
     */
    public static boolean transactionAircraftChange(Integer flight_id, Integer new_aircraft_id) throws SQLException, Exception{
        RDG.DbContext.getConnection().setAutoCommit(false);
        
        RDG.DbContext.getConnection().setTransactionIsolation(java.sql.Connection.TRANSACTION_SERIALIZABLE);
        
        boolean podarilo = false;
        Exception t=null;
        for(int i=0;i<3 &&!podarilo;i++){
            podarilo=true;
            try{
                AircraftType.canReplaceAirplane(new_aircraft_id, flight_id);
                SeatCount.changeBookedSeats(new_aircraft_id, flight_id);
                Flight.updateAircraftType(flight_id, new_aircraft_id);
            }catch(Exception e){
                t=e;
                RDG.DbContext.getConnection().rollback();
                podarilo=false;
            }
        }
        if(podarilo){
            RDG.DbContext.getConnection().commit();
            RDG.DbContext.getConnection().setAutoCommit(true);
            return true;
        }
        System.err.println(t);
        RDG.DbContext.getConnection().rollback();
        RDG.DbContext.getConnection().setAutoCommit(true);
        return false;
    }
}
