package com.nisum.mytime.service;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Time;
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.repository.EmployeeAttendanceRepo;
import com.nisum.mytime.utils.MyTimeLogger;
import com.nisum.mytime.utils.MyTimeUtils;

@Component
@Transactional                      
public class EmployeeDataService {

	private Connection connection = null;
	private Statement statement = null;
	private ResultSet resultSet = null;


	@Autowired
	private EmployeeAttendanceRepo employeeLoginsRepo;

	public List<EmpLoginData> fetchEmployeeLoginsBasedOnDates(long employeeId, String fromDate, String toDate)
			throws MyTimeException {
		long start_ms = System.currentTimeMillis();
			String querys="select emp.EmployeeCode,emp.FirstName,MIN(tr.aDateTime) AS FirstLogin,MAX(tr.aDateTime) AS LastLogin\n" + 
					"from Transactions as tr,EmployeeMaster as emp\n" + 
					"where tr.EmployeemasterID=emp.EmployeeMasterID and \n" + 
					"replace(convert(varchar,tr.aDateTime, 111), '/', '-')>='"+fromDate+"' and \n" +   
					"replace(convert(varchar,tr.aDateTime, 111), '/', '-')<='"+toDate+"' and  emp.EmployeeCode="+employeeId+"\n" + 
					"group by convert(varchar,tr.aDateTime, 111),emp.EmployeeCode,emp.FirstName";       
		
		int countHours = 0;         
		List<EmpLoginData> listOfEmpLoginData = new ArrayList<>();

		try {
			if (employeeId > 0) {  

				String dbURL = MyTimeUtils.driverUrl;
				MyTimeLogger.getInstance().info(dbURL);
				connection = DbConnection.getDBConnection(dbURL);      
				System.out.println("Connection established");      
				statement = connection.createStatement();
				resultSet = statement.executeQuery(querys.toString());     
				while (resultSet.next()) {                 
					EmpLoginData empLoginData = new EmpLoginData();     
					empLoginData.setEmployeeId(resultSet.getString(1));
					empLoginData.setEmployeeName(resultSet.getString(2));
					empLoginData.setDateOfLogin(resultSet.getDate(3).toString());
					empLoginData.setFirstLogin(resultSet.getTime(3).toString());   
					empLoginData.setLastLogout(resultSet.getTime(4).toString());    
					Time from = resultSet.getTime(3);
					Time to = resultSet.getTime(4);     
					long milliseconds=to.getTime() - from.getTime();
				    int seconds = (int) milliseconds / 1000;
				    int hours = seconds / 3600;    
				    int minutes = (seconds % 3600) / 60;              
				    seconds = (seconds % 3600) % 60;                 

					empLoginData.setTotalLoginTime(hours+":"+minutes+":"+seconds);           
					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));

			} else if (employeeId == 0) {
				
				listOfEmpLoginData = null;

				MyTimeLogger.getInstance().info("Time Taken for with fecth All Employees data based on Dates :::  "
						+ (System.currentTimeMillis() - start_ms));
			}
		} catch (Exception e) {
			MyTimeLogger.getInstance().error(e.getMessage());
			throw new MyTimeException(e.getMessage());
		}

		return listOfEmpLoginData;
	}
}