package TS;

import RDG.Passenger;
import java.sql.SQLException;

/**
 *
 * @author Marcel
 */
public class BuyTicketTS {
    /**
     * buy ticket
     * isolation level: serializable
     * - check if can replace aircraft
     * - change booked seats
     * - change aircraft type
     * @param flight_id to which flight
     * @param class_id on which class
     * @param passenger_id for who
     * @param name if passenger don't exist, then insert passenger w/ this name
     * @param id_card  if passenger don't exist, then insert passenger w/ this id_card
     * @throws SQLException
     * @throws Exception
     * @return boolean if everything went right 
     */
    public static boolean transactionBuyTicket(Integer flight_id, Integer class_id, Integer passenger_id, String name, String id_card) 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++){
            try{
                if(passenger_id==-1){
                    passenger_id=Passenger.insert(name, id_card);
                }
                if(RDG.BoughtTicket.can_reserve_ticket(flight_id, class_id)){
                    RDG.BoughtTicket.insert(flight_id, class_id, false, passenger_id);
                    podarilo=true;
                }
            }catch(Exception e){
                t=e;
                RDG.DbContext.getConnection().rollback();
                podarilo=false;
            }
        }
        if(podarilo){
            RDG.DbContext.getConnection().commit();
            RDG.DbContext.getConnection().setAutoCommit(true);
            return true;
        }
        if(t!=null)
            System.err.println(t);
        RDG.DbContext.getConnection().rollback();
        RDG.DbContext.getConnection().setAutoCommit(true);
        return false;
    }
}