package com.informatika.ojek.webservice;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.sql.*;
import javax.jws.WebService;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.json.*;

//Service Implementation
@WebService(endpointInterface = "com.informatika.ojek.webservice.IOrder")
public class Order implements IOrder {
    final public static String IDENTITY_SERVICE_SERVER = "http://localhost:8083";

    @Override
    public Account[] getPrefferedDriver(String access_token, String preffered_driver, String picking_point, String destination){
        boolean valid = validateToken(access_token);
        //cek akses token

        int id_active;
        if(valid){
            id_active =  1;
        } else {
            System.err.println("data invalid");
            return null;
        }

        try
        {
            // create our mysql database connection
            String myDriver = "com.mysql.jdbc.Driver";
            String myUrl = "jdbc:mysql://localhost/db_ojek";
            Class.forName(myDriver);
            Connection conn = DriverManager.getConnection(myUrl, "root", "");

            // our SQL SELECT query.
            // if you only need a few columns, specify them by name instead of using "*"
            String query = "SELECT distinct pref_loc.IDDriver, rating,totalvote FROM (pref_loc join rating_driver) where pref_loc.IDDriver != "+id_active+" and isdriver = 1  and (Location = '"+picking_point+"' or Location = '"+destination+"')";

            // create the java statement
            Statement st = conn.createStatement();

            // execute the query, and get a java resultset
            ResultSet rs = st.executeQuery(query);
            rs.last();
            int rowsNumber = rs.getRow();
            int n= 0;
            rs.beforeFirst();
            // iterate through the java resultset
            Account[] accounts =  new Account[rowsNumber];
            while (rs.next())
            {
                //dapetin detail akun dari user id

                String name = "aa";
                if(name.equals(preffered_driver)){
                    Account baru = new Account(1, "aaa", "aaa", "aaa@", "sss", "0808" , "ssss",false);
                    accounts[n] = baru;
                    n++;
                }
                // print the results
            }
            st.close();
            return  accounts;
        }
        catch (Exception e)
        {
            System.err.println("Got an exception! ");
            System.err.println(e.getMessage());
            return null;

        }

    }
    @Override
    public Account[] getNonPrefferedDriver(String access_token, String preffered_driver, String picking_point, String destination){
        boolean valid = validateToken(access_token);
        //cek akses token

        int id_active;
        if(valid){
            id_active =  1;
        } else {
            System.err.println("data invalid");
            return null;
        }

        try
        {
            // create our mysql database connection
            String myDriver = "com.mysql.jdbc.Driver";
            String myUrl = "jdbc:mysql://localhost/db_ojek";
            Class.forName(myDriver);
            Connection conn = DriverManager.getConnection(myUrl, "root", "");

            // our SQL SELECT query.
            // if you only need a few columns, specify them by name instead of using "*"
            String query = "SELECT distinct pref_loc.IDDriver, rating,totalvote FROM (pref_loc join rating_driver) where pref_loc.IDDriver != "+id_active+" and isdriver = 1  and (Location = '"+picking_point+"' or Location = '"+destination+"')";

            // create the java statement
            Statement st = conn.createStatement();

            // execute the query, and get a java resultset
            ResultSet rs = st.executeQuery(query);
            rs.last();
            int rowsNumber = rs.getRow();
            int n= 0;
            rs.beforeFirst();
            // iterate through the java resultset
            Account[] accounts =  new Account[rowsNumber];
            while (rs.next())
            {
                //dapetin detail akun dari user id

                String name = "aa";
                if(!name.equals(preffered_driver)){
                    Account baru = new Account(1, "aaa", "aaa", "aaa@", "sss", "0808" , "ssss",false);
                    accounts[n] = baru;
                    n++;
                }
                // print the results
            }
            st.close();
            return  accounts;
        }
        catch (Exception e)
        {
            System.err.println("Got an exception! ");
            System.err.println(e.getMessage());
            return null;

        }


    }
    @Override public boolean PuttransactionDetails(String access_token,  int id_driver, String picking_point, String destination, int rating, String comment){
        boolean valid = validateToken(access_token);
        //cek akses token

        int id_active;
        if(valid){
            id_active =  1;
        } else {
            System.err.println("data invalid");
            return false;
        }
        try
        {
            // create our mysql database connection
            String myDriver = "com.mysql.jdbc.Driver";
            String myUrl = "jdbc:mysql://localhost/db_ojek";
            Class.forName(myDriver);
            Connection conn = DriverManager.getConnection(myUrl, "root", "");

            // our SQL SELECT query.
            // if you only need a few columns, specify them by name instead of using "*"

            // create the java statement
            Statement st = conn.createStatement();
            String query1 = "SELECT * FROM transaction";
            ResultSet rs = st.executeQuery(query1);
            rs.last();
            int rowsNumber = rs.getRow();
            System.out.write(rowsNumber);
            int id_transaksi = rowsNumber +1;

            DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
            Date date = new Date();

            String query2 = "INSERT INTO transaction (IDTransaksi, IDDriver,IDPenumpang,LokasiAwal,LokasiTujuan,Rating,Comment,IsHide, DatePosted) VALUES ('"+id_transaksi+"','"+id_driver+"','"+id_active+"','"+picking_point+"','"+destination+"','"+rating+"','"+comment+"',"+0+",'"+dateFormat.format(date)+"')";
            st.executeUpdate(query2);

            String query3 = "SELECT IDTransaksi from transaction where IDDriver = '"+id_driver+"'";
            rs = st.executeQuery(query3);
            rs.last();
            int totalvote = rs.getRow();
            String query4 = "SELECT sum(rating) as a from transaction where IDDriver = '"+id_driver+"' group by IDDriver";
            rs = st.executeQuery(query4);
            rs.next();
            float totalrating = rs.getFloat("a");
            float driverrating = totalrating/totalvote;
            String query5 = "UPDATE rating_driver SET   rating='"+driverrating+"', totalvote='"+totalvote+"' WHERE IDDriver='"+id_driver+"'";
            st.executeUpdate(query5);
            st.close();
            return  true;
        }
        catch (Exception e)
        {
            System.err.println("Got an exception! ");
            System.err.println(e.getMessage());
            e.printStackTrace();
            return false;

        }


    }

    public boolean validateToken(String token){
        String urlParameters  = "token="+token;
        byte[] postData       = urlParameters.getBytes( StandardCharsets.UTF_8 );
        int    postDataLength = postData.length;
        String request        = IDENTITY_SERVICE_SERVER + "/validate";
        URL url = null;

        try {
            url = new URL(request);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput( true );
            conn.setInstanceFollowRedirects( false );
            conn.setRequestMethod("POST");
            conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty( "charset", "utf-8");
            conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
            conn.setUseCaches( false );
            DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
            wr.write(postData);
            wr.flush();
            wr.close();

            int responseCode = conn.getResponseCode();
            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Post parameters : " + urlParameters);
            System.out.println("Response Code : " + responseCode);

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            //print result
            System.out.println(response.toString());


            JSONObject obj = new JSONObject(response.toString());
            String data = obj.getString("data");

            if(data.equals("valid")){
                return true;
            } else
            {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}