package RDG;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import javax.sql.DataSource;
import org.postgresql.ds.PGSimpleDataSource;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 *
 * @author Marcel
 */
public class Searchings {
    /**
    * observe how many times was some flight searched by some user
    * @throws SQLException
    * @param departure_id departure city
    * @param arrival_id arrival city
    * @param user_id user, who searched this flight
    * @return count, how many times
    */
    public static Integer num(Integer departure_id, Integer arrival_id, Integer user_id) throws SQLException{
        PreparedStatement s = DbContext.getConnection().prepareStatement("SELECT * from searchings where departure_city_id=? and arrival_city_id=? and user_id=?");
        s.setInt(1, departure_id);
        s.setInt(2, arrival_id);
        s.setInt(3, user_id);
        ResultSet rs = s.executeQuery();
        while(rs.next()){
            return rs.getInt("count");
        }
        return 0;
    }
    /**
    * increment searched count for flight and user
    * @param departure_id departure city
    * @param arrival_id arrival city
    * @param user_id user, who searched
    * @throws SQLException
    */
    public static void plus(Integer departure_id, Integer arrival_id, Integer user_id) throws SQLException, Exception{
        if(Searchings.num(departure_id, arrival_id, user_id)==0){
            PreparedStatement s = DbContext.getConnection().prepareStatement("INSERT INTO searchings (\"count\", user_id, departure_city_id, arrival_city_id) values (1,?,?,?)");
            s.setInt(1, user_id);
            s.setInt(2, departure_id);
            s.setInt(3, arrival_id);
            s.executeUpdate();
            try (ResultSet r = s.getGeneratedKeys()) {
                r.next();
            }
            return;
        }
        PreparedStatement s = DbContext.getConnection().prepareStatement("UPDATE searchings set \"count\"=\"count\"+1 where departure_city_id=? and arrival_city_id=? and user_id=?");
        s.setInt(1, departure_id);
        s.setInt(2, arrival_id);
        s.setInt(3, user_id);
        s.executeUpdate();
        //System.out.println(s.getUpdateCount());
    }
}
