package com.nisum.mytime.service;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Calendar; 
import java.util.GregorianCalendar;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

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

@Service
public class AttendanceServiceImpl implements AttendanceService {


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

	@Override
	public List getAttendanciesReport(String reportDate) throws MyTimeException, SQLException {
		long start_ms = System.currentTimeMillis();
		List listOfEmployees = new ArrayList<>();
		String querys="select distinct emp.EmployeeCode,emp.FirstName,'P' as AttStatus\n" + 
				"				FROM [smartiSCC].[dbo].[Transactions] as tr,[smartiSCC].[dbo].[EmployeeMaster] as emp\n" + 
				"				where tr.EmployeemasterID=emp.EmployeeMasterID and \n" + 
				"				replace(convert(varchar,tr.aDateTime, 111), '/', '-')='"+reportDate+"'\n" + 
				"		Union \n" + 
				"		select  emp.EmployeeCode,emp.FirstName,'A' as AttStatus\n" + 
				"				FROM [smartiSCC].[dbo].[Transactions] as tr,[smartiSCC].[dbo].[EmployeeMaster] as emp\n" + 
				"				where tr.EmployeemasterID!=emp.EmployeeMasterID and \n" + 
				"				replace(convert(varchar,tr.aDateTime, 111), '/', '-')='"+reportDate+"'";     
			try {   
			String dbURL = MyTimeUtils.driverUrl;      
			MyTimeLogger.getInstance().info(dbURL);   
			connection = DbConnection.getDBConnection(dbURL);         
			statement = connection.createStatement();      
			resultSet = statement.executeQuery(querys.toString());
			while (resultSet.next()) {  
				AttendenceData attendData=new AttendenceData();      
				attendData.setEmployeeId(resultSet.getString(1));    
				attendData.setEmployeeName(resultSet.getString(2));
				attendData.setIfPresent(resultSet.getString(3));     
				listOfEmployees.add(attendData);          
		        }        
				MyTimeLogger.getInstance().info("Time Taken for " + (System.currentTimeMillis() - start_ms));
			} catch (Exception e) {
				MyTimeLogger.getInstance().error("Exception occured due to : ", e);
				throw new MyTimeException(e.getMessage());
			}finally {
			if (null != connection) {
				connection.close();          
				statement.close();           
				resultSet.close();
			}     
		}
		return listOfEmployees;
		
	}

}
