package logic;

import io.keen.client.java.KeenClient;
import io.swagger.model.Car;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Christoph See on 01/02/2017.
 * Student ID: S1510770012
 */
public class Handler {

    private DBConnect db;

    public Handler(String dbtype){
        if(dbtype=="Postgresql"){
            db = new DBConnectPostgresql();
        }
        if(dbtype=="Redis"){
            db = new DBConnectRedis();
        }
    }

    /**
     * Inserts a new car into the database
     * @param Poccupancy The occupancy of the car
     * @param Pavailability The availability of the car
     * @param PstateOfCharge The state of charge of the car
     * @param PlicensePlate The license plate of the car
     */
    public Car insertNewCar (Integer Poccupancy, Boolean Pavailability, Integer PstateOfCharge, String PlicensePlate){
        return db.insertNewCar(Poccupancy, Pavailability, PstateOfCharge, PlicensePlate);
    }

    /**
     * Updates a car in the database
     * @param cid The id of the car
     * @param Poccupancy The occupancy of the car
     * @param Pavailability The availability of the car
     * @param PstateOfCharge The state of charge of the car
     * @param PlicensePlate The license plate of the car
     */
    public void updateCar (Integer cid, Integer Poccupancy, Boolean Pavailability, Integer PstateOfCharge, String PlicensePlate){
        if(Pavailability){
            try {
                SendMail.sendmail(cid);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        db.updateCar(cid, Poccupancy, Pavailability, PstateOfCharge, PlicensePlate);
    }

    /**
     * Deletes a car from the database
     * @param cid The id of the car to delete
     */
    public void deleteCar (Integer cid){
        db.deleteCar(cid);
    }

    /**
     * Queries a car in the database
     * @param cid The id of the car to request
     * @return A Car Object
     */
    public Car getCarById (Integer cid) {
        track(cid);
        return db.setSingleCarQuery(cid);
    }

    /**
     * Queries all cars in the database
     * @return A Car Object
     */
    public List<Car> getAllCars () {

        return db.setAllCarsQuery();
    }

    protected void track(Integer cid) {
        // Create an event to upload to Keen.
        Map<String, Object> event = new HashMap<String, Object>();
        event.put("item", "Car " + cid + " got rented");

        // Add it to the "purchases" collection in your Keen Project.
        KeenClient.client().addEvent("New Car rented", event);
    }
}
