package json_package;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Base64;
import java.util.Date;
import java.util.Map;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import main_package.DataBaseConnection;
import main_package.DataBaseMethods;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

@ViewScoped
@ManagedBean(name="myNidhiEmpAttendance")

public class MyNidhiEmpAttendanceJsonBean implements Serializable
{   
	String json;
	
	Date logDate, logTime;

	DataBaseMethods obj = new DataBaseMethods();
	
	public MyNidhiEmpAttendanceJsonBean() throws ParseException 
	{   
		Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
              
		String  userid = params.get("userid");
		String dt = params.get("dt");
		String latitude = params.get("latitude");
		String longitude = params.get("longitude");
		String attType = params.get("attType");
		String deviceName = params.get("deviceName");
		String branchStr = params.get("branchId");
		int branchId = Integer.valueOf(branchStr);
		String selfie = params.get("selfie");
		
		
		if (selfie == null)
		{
			selfie = "";
		}
				 
		
		if(userid.contains("'") || dt.contains("'") || latitude.contains("'") || longitude.contains("'") || 
		   attType.contains("'") || deviceName.contains("'"))
		{
			userid="";
			dt="";
			latitude="";
			longitude="";
			attType="";
			deviceName="";
		}
		
		/*String mobile=params.get("mobile");
		String pwd=params.get("pwd");*/
		/*DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
		if(dt!=null && !dt.equals(""))
		{
			startDate = (Date)formatter.parse(dt);
		}*/

		/*System.out.println(userid);
		System.out.println(dt);
		System.out.println(latitude);
		System.out.println(longitude);
		System.out.println(attType);
		System.out.println(deviceName);*/
		
		
		
		String selfiePath = "";

        if (selfie != null && !selfie.trim().equals(""))
    	{
    	    try
    	    {
    	        String extension = ".jpg";

    	        if (selfie.startsWith("data:image/png"))
    	        {
    	            extension = ".png";
    	        }
    	        else if (selfie.startsWith("data:image/jpeg"))
    	        {
    	            extension = ".jpg";
    	        }
    	        else if (selfie.startsWith("data:image/jpg"))
    	        {
    	            extension = ".jpg";
    	        }
    	        else if (selfie.startsWith("data:image/webp"))
    	        {
    	            extension = ".webp";
    	        }

    	        if (selfie.contains(","))
    	        {
    	            selfie = selfie.substring(selfie.indexOf(",") + 1);
    	        }

    	        selfie = selfie.replace(' ', '+');

    	        selfie = selfie.replace("\r", "").replace("\n", "").replace("\t", "");

    	        byte[] fileBytes = Base64.getDecoder().decode(selfie);

    	        String fileName = "selfie_" + System.currentTimeMillis() + extension;

    	        selfiePath = fileName;

    	        InputStream in = new ByteArrayInputStream(fileBytes);

    	        obj.makeProfile(in, selfiePath);

    	        in.close();
    	    }
    	    catch (Exception e)
    	    {
    	        e.printStackTrace();

    	        selfiePath = "";
    	    }
    	}
		
		
		
		int i = 0;
		
		Connection conn=DataBaseConnection.JAVAConnection();
		
		String logDt=dt.substring(0, 10);
		String logTm=dt.substring(11, 19);
		
		
		
		try {
			if (logDt.matches("\\d{2}-\\d{2}-\\d{4}")) {
				java.text.SimpleDateFormat inputFormat = new java.text.SimpleDateFormat("dd-MM-yyyy");

				java.text.SimpleDateFormat outputFormat = new java.text.SimpleDateFormat("yyyy-MM-dd");

				inputFormat.setLenient(false);

				logDt = outputFormat.format(inputFormat.parse(logDt));
			}
		} catch (java.text.ParseException e) {
			e.printStackTrace();
		}
		
		
		System.out.println("hit before login");
		System.out.println("logDt = " + logDt);
		System.out.println("Dt (attendance_Date)= " + dt);
		System.out.println("selfie path = " + selfie);
		
		
		System.out.println("hit before login");
		if(attType.equalsIgnoreCase("login"))
		{
			System.out.println("login method hitted.");
			i=obj.insertInAttendanceTable(branchId,userid, logDt, logTm, latitude, longitude, deviceName, conn, selfiePath);
		}
		else
		{
			i=obj.updateInAttendanceTable(branchId,userid, logDt, logTm, latitude, longitude, deviceName, conn,selfiePath);
		}
	    
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		JSONObject mainobj = new JSONObject();
		JSONArray arr=new JSONArray();
		JSONObject obj = new JSONObject();
				
	    	 String status="";
	    	 if(i>=1)
	    	 {
	    		 status="You Have Successfully "+attType+" At "+logTime+" Thank You. ";
	    	 }
	    	 else
	    	 {
	    		status="Something went wrong.";
	    	 }
	    	
	    	 obj.put("st",status);
	    	  
		     arr.add(obj); 
		      

	    mainobj.put("track", arr);

		json=mainobj.toJSONString();
	
		//int i=new DatabaseMethods1().news(concern);
		  
	}
	
	
	
	public void renderJson() throws IOException {
 	    FacesContext facesContext = FacesContext.getCurrentInstance();
 	    ExternalContext externalContext = facesContext.getExternalContext();
 	    externalContext.setResponseContentType("application/json");
 	    externalContext.setResponseCharacterEncoding("UTF-8");
 	    externalContext.getResponseOutputWriter().write(json);
 	    facesContext.responseComplete();
 	    
 	    
 	}

	public String getJson() {
		return json;
	}

	public void setJson(String json) {
		this.json = json;
	}
}
