package com.nisum.mytime.service;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Time;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.nisum.mytime.configuration.DbConnection;
import com.nisum.mytime.exception.handler.MyTimeException;
import com.nisum.mytime.model.EmpLoginData;
import com.nisum.mytime.utils.MyTimeLogger;
import com.nisum.mytime.utils.MyTimeUtils;

@Component
@Transactional
public class EmployeeDataService {

    @Autowired
    DbConnection dbConnection;

    public List<EmpLoginData> fetchEmployeeLoginsBasedOnDates(long employeeId, String fromDate, String toDate) throws MyTimeException {
    	
    	System.out.println("---------------Generate Report------------");
    	
    	//Checking Condition whether fromDate and Todate are having the Time
    	if(fromDate.length()>10) {
    		// Converting the Time from AM/PM to 24 Hours Format
    	    DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm aa");
    	    DateFormat outputformat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    	    String fromDateIn24Hours=null;
    	    String toDateIn24Hours=null;
    	    try {
				 fromDateIn24Hours = outputformat.format(df.parse(fromDate));
				 toDateIn24Hours = outputformat.format(df.parse(toDate));
			} catch (ParseException e) {
				System.out.println("Exception While Converting String to Date");
			}
    	    // Getting only hours from Date and Time
    		int from=Integer.parseInt(fromDateIn24Hours.substring(11,13));
    		int to=Integer.parseInt(toDateIn24Hours.substring(11,13));
    		//if from is greater than the to time 
    		if(to<from) {
    			// Get the Date from Date and Time
    			fromDate=fromDate.substring(0,11);
    			toDate=fromDate.substring(0,11);
    			// Increasing the to Date to next time because of from time is greater than the to time
    			LocalDate newtoDate = LocalDate.parse(toDate).plusDays(1);	
    			toDate=newtoDate.toString();
    		}
    		
    	}
        long start_ms = System.currentTimeMillis();
        String querys = null;
        if (employeeId == 0) {
            querys = MyTimeUtils.ABESENT_STATUS_QUERY + "'" + fromDate.replace("-", "/") + "'"
                    + MyTimeUtils.ABESENT_STATUS_QUERY1 + "'" + toDate.replace("-", "/") + "'"
                    + MyTimeUtils.ABESENT_STATUS_QUERY3;
        } else {
            querys = MyTimeUtils.ABESENT_STATUS_QUERY + "'" + fromDate.replace("-", "/") + "'"
                    + MyTimeUtils.ABESENT_STATUS_QUERY1 + "'" + toDate.replace("-", "/") + "'"
                    + MyTimeUtils.ABESENT_STATUS_QUERY2 + employeeId
                    + MyTimeUtils.ABESENT_STATUS_QUERY3;
            System.out.println("Query from fetchEmployeeLoginsBasedOnDates "+querys);
        }
        int countHours = 0;
        List<EmpLoginData> listOfEmpLoginData = new ArrayList<>();
        long totalseconds =0;
        try (Connection connection = dbConnection.getDBConnection();
                Statement statement = connection.createStatement();
                ResultSet resultSet = statement.executeQuery(querys.toString())) {
            while (resultSet.next()) {
                EmpLoginData empLoginData = new EmpLoginData();
                empLoginData.setEmployeeId(resultSet.getString("EmployeeCode"));
                empLoginData.setEmployeeName(resultSet.getString("FirstName"));
                empLoginData.setDateOfLogin(resultSet.getDate("FirstLogin").toString());
                empLoginData.setFirstLogin(resultSet.getTime("FirstLogin").toString());
                empLoginData.setLastLogout(resultSet.getTime("LastLogin").toString());
                
                
             int start=  resultSet.getTime("FirstLogin").getHours();
              int end=resultSet.getTime("LastLogin").getHours();
                if(end<start){
               LocalDateTime loginTime= resultSet.getTimestamp("FirstLogin").toLocalDateTime();
               LocalDateTime logoutTime= resultSet.getTimestamp("LastLogin").toLocalDateTime();
               
      	      totalseconds = java.time.Duration.between(loginTime, logoutTime).getSeconds();
            }
            else {
                Time from = resultSet.getTime("FirstLogin");
                Time to = resultSet.getTime("LastLogin");
                long milliseconds = to.getTime() - from.getTime();
                 totalseconds = (int) milliseconds / 1000;
            }
                int hours = (int) (totalseconds / 3600);
                int minutes = (int) ((totalseconds % 3600) / 60);
               int seconds = (int) ((totalseconds % 3600) % 60);
            
                empLoginData.setTotalLoginTime(hours + ":" + minutes + ":" + seconds);
                Date d = MyTimeUtils.tdf.parse(empLoginData.getTotalLoginTime());
                countHours += d.getTime();
                listOfEmpLoginData.add(empLoginData);
            }
            if (!listOfEmpLoginData.isEmpty()) {
                listOfEmpLoginData.get(0).setTotalAvgTime(MyTimeUtils.tdf.format(countHours / listOfEmpLoginData.size()));
            }
            MyTimeLogger.getInstance().info(" Time Taken fecth Employee data based on Dates ::: " + (System.currentTimeMillis() - start_ms));
        } catch (Exception e) {
            e.printStackTrace();
            MyTimeLogger.getInstance().error(e.getMessage());
            throw new MyTimeException(e.getMessage());
        }
        return listOfEmpLoginData;
    }
    

    public List<EmpLoginData> fetchEmployeeLoginsBasedOnDates1(long employeeId, String fromDate, String nextDate,String toDate) throws MyTimeException {
    	int differentBetweenDays=Period.between(LocalDate.parse(fromDate), LocalDate(toDate)).getDays();
    	long start_ms = System.currentTimeMillis();
        String querys = null;
        List<EmpLoginData> listOfEmpLoginData = new ArrayList<>();
        for(int i=1;i<=differentBetweenDays;i++) { 
            querys ="select emp.EmployeeCode,emp.FirstName,MIN(tr.aDateTime) AS FirstLogin,MAX(tr.aDateTime) AS LastLogin\r\n" + 
            		"from [smartiSCC].[dbo].[Transactions] as tr,[smartiSCC].[dbo].[EmployeeMaster] as emp\r\n" + 
            		"where tr.EmployeemasterID=emp.EmployeeMasterID  and \r\n" + 
            		"tr.aDateTime >= '2018/08/11 22:00' and tr.aDateTime<= '2018/08/12 10:00' \r\n" + 
            		"and  emp.EmployeeCode = 16107 group by  emp.EmployeeCode,\r\n" + 
            		" emp.FirstName";
            System.out.println("Query from fetchEmployeeLoginsBasedOnDates "+querys);
        int countHours = 0;
        long totalseconds =0;
        try (Connection connection = dbConnection.getDBConnection();
                Statement statement = connection.createStatement();
                ResultSet resultSet = statement.executeQuery(querys.toString())) {
            while (resultSet.next()) {
                EmpLoginData empLoginData = new EmpLoginData();
                empLoginData.setEmployeeId(resultSet.getString("EmployeeCode"));
                empLoginData.setEmployeeName(resultSet.getString("FirstName"));
                empLoginData.setDateOfLogin(resultSet.getDate("FirstLogin").toString());
                empLoginData.setFirstLogin(resultSet.getTime("FirstLogin").toString());
                empLoginData.setLastLogout(resultSet.getTime("LastLogin").toString());
                                
              int start=  resultSet.getTime("FirstLogin").getHours();
              int end=resultSet.getTime("LastLogin").getHours();
                if(end<start){
               LocalDateTime loginTime= resultSet.getTimestamp("FirstLogin").toLocalDateTime();
               LocalDateTime logoutTime= resultSet.getTimestamp("LastLogin").toLocalDateTime();
               
      	      totalseconds = java.time.Duration.between(loginTime, logoutTime).getSeconds();
            }
            else {
                Time from = resultSet.getTime("FirstLogin");
                Time to = resultSet.getTime("LastLogin");
                long milliseconds = to.getTime() - from.getTime();
                 totalseconds = (int) milliseconds / 1000;
            }
                int hours = (int) (totalseconds / 3600);
                int minutes = (int) ((totalseconds % 3600) / 60);
               int seconds = (int) ((totalseconds % 3600) % 60);
            
                empLoginData.setTotalLoginTime(hours + ":" + minutes + ":" + seconds);
                Date d = MyTimeUtils.tdf.parse(empLoginData.getTotalLoginTime());
                countHours += d.getTime();
                listOfEmpLoginData.add(empLoginData);
            }
            if (!listOfEmpLoginData.isEmpty()) {
                listOfEmpLoginData.get(0).setTotalAvgTime(MyTimeUtils.tdf.format(countHours / listOfEmpLoginData.size()));
            }
            MyTimeLogger.getInstance().info(" Time Taken fecth Employee data based on Dates ::: " + (System.currentTimeMillis() - start_ms));
        } catch (Exception e) {
            e.printStackTrace();
            MyTimeLogger.getInstance().error(e.getMessage());
            throw new MyTimeException(e.getMessage());
        }
   }
        return listOfEmpLoginData;
    }


	private LocalDate LocalDate(String toDate) {
		// TODO Auto-generated method stub
		return null;
	}
}