package com.csc.library.databean;

import com.csc.library.utilities.MyLog;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.StringTokenizer;

import std.library.TimeSpan;

import com.csc.library.database.FieldManager;
import com.csc.library.database.MyHashMap;
import com.csc.library.database.StaticConfig;
import com.csc.library.session.DbInquiry;
import com.csc.library.session.DbRecord;
import com.csc.library.session.DbTable;
import com.csc.library.session.InitialInquiry;
import com.csc.library.session.InitialRecord;
import com.csc.library.session.RecordCmp;
import com.csc.library.utilities.CscCalendar;
import com.csc.library.utilities.CscTime;
import com.csc.library.utility.DiffTime;

/*
 * �红����š�÷ӧҹ�ͧ��ѡ�ҹ
 */
public class Ttime_current extends RecordCmp {
	
	private DbRecord empRec;
	private DbInquiry inqTime1 = null;
	private DbRecord recPayroll = null;
	private DbRecord recHistory = null;	
	private DecimalFormat df = new DecimalFormat("0.00");
	private HashMap shiftProp ;
		
	public Ttime_current() {
		super("Ttime_current", "Ttime_current  Table");
	}
	
	public void setShiftProp(HashMap shp){
		this.shiftProp = shp;
	}
			
	private void setEmployeeDetail(){
		try {
			DbRecord rec = this.getEmpRecord();
			this.set("emp_position",rec.getString("emp_position"));
			this.set("emp_group",rec.getString("emp_group"));				
			this.set("branch",rec.getString("branch"));
			this.set("jobcode",rec.getString("job"));
			this.set("bu1",rec.getString("bu1"));
			this.set("bu2",rec.getString("bu2"));
			this.set("bu3",rec.getString("bu3"));
			this.set("bu4",rec.getString("bu4"));
			this.set("bu5",rec.getString("bu5"));
			this.set("bossid",rec.getString("bossid"));
			this.set("emp_level",rec.getString("emp_level"));
			this.set("costcenter",rec.getString("costcenter"));
			this.set("salatype",rec.getString("salatype"));
			this.set("currency",rec.getString("costcenter"));
			this.set("salary",rec.getString("salary"));
			this.set("every",rec.getString("emp_every"));
			this.set("workarea",rec.getString("workarea"));			
		} catch (Exception e) {
			MyLog.error(this, e);			
		}		
	}
		
	/*
	 * �ӡ�������âҴ �� ��� �ͷ� �ͧ��ѡ�ҹ������ѹ
	 */
	public void calulateSumDatainChild() {
		String event = "";
		CscTime lt = new CscTime(0f);
		CscTime lv = new CscTime(0f);
		CscTime ot = new CscTime(0f);
		CscTime absent = new CscTime(0f);
		CscTime ot1 = new CscTime(0f);
		CscTime ot5 = new CscTime(0f);
		CscTime ot2 = new CscTime(0f);
		CscTime ot3 = new CscTime(0f);	
		CscTime hour = new CscTime(0f);
		CscTime ap_ot = new CscTime(0f);
		
		double unused1=0;
		double unused2=0;
		double unused3=0;
		double unused4=0;
		double unused5=0;
		String date_actual = "";
		try {
			DbTable db = (DbTable) this.getChild("ttime_current1");	
			int count = db.recCount();
			db.first();			
			do{				
				DbRecord rec = (DbRecord) db.getCurrentRecordManager();	
				rec.getString("action");
				
				/* ��Ǩ�ͺ ��. ������ѹ ��� ��. �ͧ�з���ѹ�����ҡѺ ��. �ӧҹ�ͧ����ѡ (Time0id 㹵��ҧ Memployee) ���������ѹ����ִ ��. �ӧҹ�ͧ����ѡ  */
				if(rec.getString("doctype").equals("A") && count == 1){ /* ������ѹ */
					float hour_d = Float.parseFloat(((String)shiftProp.get("HOUR_D")));
					if(hour_d != rec.getFloat("m_lv")){
						rec.set("m_lv", hour_d);
					}
				}
				
				lt.add(rec.getFloat("lt"));				
				ot.add(rec.getFloat("ac_ot"));
				
				if (rec.getString("tr_type").indexOf("A")>-1) {
					lv.add(rec.getFloat("m_lv"));
				} else { 
					absent.add(rec.getFloat("m_lv"));
				}
				
				if (rec.getString("eventgrp").equals("H") || rec.getString("eventgrp").equals("I")) {
					event = rec.getString("eventgrp");
				}
					
				ot1.add(rec.getFloat("ot1"));
				ot5.add(rec.getFloat("ot5"));
				ot2.add(rec.getFloat("ot2"));
				ot3.add(rec.getFloat("ot3"));
				hour.add(rec.getFloat("hour_d"));
				ap_ot.add(rec.getFloat("ap_ot"));
				
				unused1 += rec.getDouble("unused1"); 
				unused2 += rec.getDouble("unused2"); 
				unused3 += rec.getDouble("unused3"); 
				unused4 += rec.getDouble("unused4"); 
				unused5 += rec.getDouble("unused5"); 
				
				date_actual = rec.getString("date_actual");
				db.next();				
			} while (!db.eof());					
			
		} catch (Exception e) {
			MyLog.error(this, e);			
		}		
		
		this.set("eventgrp", event);
		this.set("lt",lt.getFloat());
		
		this.set("absent",absent.getFloat());
		this.set("lv",lv.getFloat());
		this.set("ot",ot.getFloat());		
		this.set("ot1", ot1.getFloat());
		this.set("ot5", ot5.getFloat());
		this.set("ot2", ot2.getFloat());
		this.set("ot3", ot3.getFloat());
		this.set("hour_d", hour.getFloat());
		this.set("unused1", unused1);
		this.set("unused2", unused2);
		this.set("unused3", unused3);
		this.set("unused4", unused4);
		this.set("unused5", unused5);
		this.set("date_actual", date_actual);
		this.set("ot_app", unused5);
	}
	
	public void setDataRecord() {
		CscCalendar csc = new CscCalendar(this.getString("dateid"));
		this.set("daytype", csc.getCSCDOW());
		//-------------- �ӡ������� �ѹ������ѹ�ӧҹ������� -------------//
		boolean chkWork = true;
		try {			
			DbTable db = (DbTable) this.getChild("ttime_current1");		
			do {
				String event = db.getCurrentRecordManager().getString("eventgrp");
				if (event.equals("H") || event.equals("I")) {
					chkWork = false;
				}
				db.next();				
			} while (!db.eof());		
		} catch (Exception e) {
			MyLog.error(this, e);
		}
		if (chkWork) {
			this.set("iswork", "1");
		} else {
			this.set("iswork", "0");
		}
		//-------------- End ----------------//
	}
	
	public boolean preInsertTrigger() {		
		try {
			super.preInsertTrigger();
			setEmployeeDetail();			
			
			//if (!this.param.containsKey("__screen")) 
                //this.calulateSumDatainChild();		
			//setDataRecord();
			
			return true;
		} catch (Exception e) {
			MyLog.error(this, e);						
			return false;
		}
	}
	
	protected boolean preUpdateTrigger() {		
		try {
			super.preUpdateTrigger();
			setEmployeeDetail();
			
			if (!this.param.containsKey("__screen")) 
                this.calulateSumDatainChild();
			setDataRecord();
			
			return true;
		} catch (Exception e) {
			MyLog.error(this, e);			
			return false;
		}
	}
		
	/*
	 * ���¢����š�÷ӧҹŧ������ѵԡ�÷ӧҹ
	 * TTIME_CURRENT ------> TTIME_HISTORY
	 * TTIME_CURRENT1 ------> TTIEM_HISTORY1
	 */
	public void moveTimeHistory() {
		DbInquiry inqChild = null;
		try {
			if (this.inqTime1 == null) {
				this.inqTime1 = new InitialInquiry(this.userPro).getDbInquiry();
				this.inqTime1.setParam(this.param);
				this.inqTime1.setSchemaName(this.userPro.getSchemaName());
				this.inqTime1.initMyTable("Ttime_current1", "", "");
				this.inqTime1.setColumn("*");	
			}
			
			DbRecord rec = this.cloneRecord(true);
			rec.setColumn("*");
			rec.putChild(this.inqTime1);
			rec.refreshChild("Ttime_current1");
			
			inqChild = (DbInquiry) rec.getChild("Ttime_current1");
			do {
				Ttime_current1 recChild = (Ttime_current1) inqChild.getCurrentDbRecord().cloneRecord(true);				
				recChild.moveTimeHistory();				
			} while (inqChild.next());
			
			if (this.recHistory == null) {
				this.recHistory = new InitialRecord(this.userPro).getDbRecord("Ttime_History");
				this.recHistory.setColumn("*");
			}
			this.recHistory.setData(this);
			this.recHistory.save();			
			
			rec.delete();
		} catch (Exception e) {
			MyLog.error(this, e);			
		}
		finally{
			try{
				inqChild.closeConnection();
				this.inqTime1.closeConnection();
			}catch(Exception e){
				MyLog.error(this, e);
			}
		}
	}
	
	/*
	 * �ӡ�� copy ��������ѧ�к��Թ��͹ ������㹡�äӹdz�Թ�״�͹����
	 * TTIME_CURRENT ----> TPTIME_CURRENT
	 * TTIME_CURRENT1 ----> TPTIME_CURRENT1
	 */
	public void moveToPayroll() {
		DbInquiry inqChild = null;
		try {
			if (this.inqTime1 == null) {
				this.inqTime1 = new InitialInquiry(this.userPro).getDbInquiry();
				this.inqTime1.setParam(this.param);
				this.inqTime1.setSchemaName(this.userPro.getSchemaName());
				this.inqTime1.initMyTable("Ttime_current1", "", "");
				this.inqTime1.setColumn("*");	
			}
			
			this.putChild(this.inqTime1);
			this.refreshChild("Ttime_current1");
			
			inqChild = (DbInquiry) this.getChild("Ttime_current1");
			do {
				Ttime_current1 recChild = (Ttime_current1) inqChild.getCurrentDbRecord().cloneRecord(true);	
				recChild.moveToPayroll();
			} while (inqChild.next());
			
			if (this.recPayroll == null) {
				this.recPayroll = new InitialRecord(this.userPro).getDbRecord("Tptime_current");
				this.recPayroll.setColumn("*");
			} 
			this.recPayroll.clearField();
			this.recPayroll.setData(this);
			this.recPayroll.save();		
		} catch (Exception e) {
			MyLog.error(this, e);
		}
		finally{
			try{
				inqChild.closeConnection();
				this.inqTime1.closeConnection();
			}catch(Exception e){
				MyLog.error(this, e);
			}
		}
	}
	
	public FieldManager getField(String fieldName) {		
		FieldManager fm = super.getField(fieldName);
		if(fieldName.equalsIgnoreCase("countempbu1")){
  	  		fm=(FieldManager)this.initField("countempbu1");  	  		
  	  	} else if(fieldName.equalsIgnoreCase("countempbu2")){
  	  		fm=(FieldManager)this.initField("countempbu2");  	  		
  	  	} else if(fieldName.equalsIgnoreCase("countempbu3")){
  	  		fm=(FieldManager)this.initField("countempbu3");  	  		
  	  	} else if(fieldName.equalsIgnoreCase("countempbu4")){
  	  		fm=(FieldManager)this.initField("countempbu4");  	  		
  	  	} else if(fieldName.equalsIgnoreCase("countempbu5")){
  	  		fm=(FieldManager)this.initField("countempbu5");  	  		
  	  	} else if(fieldName.equalsIgnoreCase("countempbranch")){
  	  		fm=(FieldManager)this.initField("countempbranch");  	  		
  	  	} else if(fieldName.equalsIgnoreCase("countempjob")){
  	  		fm=(FieldManager)this.initField("countempjob");  	  		
  	  	} else if(fieldName.equalsIgnoreCase("countempposition")){
  	  		fm=(FieldManager)this.initField("countempposition");  	  		
  	  	} else if(fieldName.equalsIgnoreCase("countemp")){
  	  		fm=(FieldManager)this.initField("countemp");  	  		
        } else if(fieldName.equalsIgnoreCase("countempempgroup")){
            fm=(FieldManager)this.initField("countempempgroup");            
        } else if (fieldName.equalsIgnoreCase("timeoutsubin")) { //�����͡ - ������Ңͧ��ѡ�ҹ ��ź�ѡ���§�͡
			try {
				CscTime c = new CscTime();			
				DbInquiry ch = (DbInquiry) this.getChild("Ttime_current1");
				do {
					DbRecord rec = ch.getCurrentDbRecord();
					CscCalendar time_in = new CscCalendar(rec.getString("m_dt_bg"));
					time_in.setCSCTime(rec.getFloat("m_tm_bg"));
					CscCalendar time_out = new CscCalendar(rec.getString("m_dt_en"));
					time_out.setCSCTime(rec.getFloat("m_tm_en"));
					CscCalendar break_in = new CscCalendar(rec.getString("dt_breakin"));
					break_in.setCSCTime(rec.getFloat("tm_breakin"));			
					CscCalendar break_out = new CscCalendar(rec.getString("dt_breakout"));
					break_out.setCSCTime(rec.getFloat("tm_breakout"));
					DiffTime dt = new DiffTime();
					float time = dt.TimeOutDiffTimeIn(time_in, time_out, break_in, break_out);
					c.add(time);
				} while (ch.next());
				ch.closeConnection();
				
				fm = this.initField("String", "", 100, 0, "");
	            fm.setWorking(true);
	            fm.setUProfile(this.userPro);
	            fm.setDescription(fieldName);
	            fm.setName(fieldName.toLowerCase());
	            fm.set(df.format(Double.parseDouble(String.valueOf(c.getFloat()))));	            
			} catch (Exception e) {
				MyLog.error(this, e);
			}
			
        } else if (fieldName.equalsIgnoreCase("OTHolidayWithoutBreak")) {
        	/**
			 * Author : Nuiss
			 * Site : PG Only
			 * Date : 05/01/2553
			 * Logic : OT �ѡ�ѡ���§�͡
			 */
			try {
				CscTime c = new CscTime();
				double otSubtarctBreak = 0.0d;
 				DbInquiry ch = (DbInquiry) this.getChild("Ttime_current1");
				do {
					DbRecord rec = ch.getCurrentDbRecord();
					//ac_ot
					float ot =rec.getFloat("ac_ot");
					//time span
					TimeSpan ts= new TimeSpan();
					ts.setSignSeperateOfDate("-");
					//work plan
					TimeSpan tsStPlanDate = new TimeSpan();
					tsStPlanDate.setSignSeperateOfDate("-");
					TimeSpan tsEndPlanDate = new TimeSpan();
					tsEndPlanDate.setSignSeperateOfDate("-");	
					//employee swipe
					TimeSpan tsStDate = new TimeSpan();
					tsStDate.setSignSeperateOfDate("-");
					TimeSpan tsEndDate = new TimeSpan();
					tsEndDate.setSignSeperateOfDate("-");	
					//break plan
					TimeSpan tsBrkStDate = new TimeSpan();
					tsBrkStDate.setSignSeperateOfDate("-");	
					TimeSpan tsBrkEndDate = new TimeSpan();
					tsBrkEndDate.setSignSeperateOfDate("-");	
					
					if(rec.getString("eventgrp").equals("H")||rec.getString("eventgrp").equals("I")){
						
						tsStPlanDate.cnvrtToTimeSpan(rec.getString("c_dt_bg"), rec.getFloat("c_tm_bg"));
						tsEndPlanDate.cnvrtToTimeSpan(rec.getString("c_dt_en"), rec.getFloat("c_tm_en"));
						
						tsStDate.cnvrtToTimeSpan(rec.getString("m_dt_bg"), rec.getFloat("m_tm_bg"));
						tsEndDate.cnvrtToTimeSpan(rec.getString("m_dt_en"), rec.getFloat("m_tm_en"));
						
						tsBrkStDate.cnvrtToTimeSpan(rec.getString("dt_breakin"), rec.getFloat("tm_breakin"));
						tsBrkEndDate.cnvrtToTimeSpan(rec.getString("dt_breakout"), rec.getFloat("tm_breakout"));
						
						double breakHour = ts.timeDiff(tsBrkStDate, tsBrkEndDate);
						if(ts.compareDateTime(tsStDate,tsBrkStDate)<=0 &&
						   ts.compareDateTime(tsEndDate,tsBrkEndDate)>=0){
							//�ٴ�ѵ� ������ǧ�ѡ���§ �� OT �ѡ�ѡ����
							otSubtarctBreak = ts.timeSubtract(ot, breakHour);
						}//end if 
					}//end if 
					c.add(Float.valueOf(String.valueOf(otSubtarctBreak)));
				} while (ch.next());
				ch.closeConnection();
				
				fm = this.initField("String", "", 100, 0, "");
	            fm.setWorking(true);
	            fm.setUProfile(this.userPro);
	            fm.setDescription(fieldName);
	            fm.setName(fieldName.toLowerCase());
	            fm.set(df.format(Double.parseDouble(String.valueOf(c.getFloat()))));	            
			} catch (Exception e) {
				MyLog.error(this, e);
			}//end try
        }//end if 
		return fm;
	}
	
	public void setEmpRecord(DbRecord rec) {
		this.empRec = rec;
		if (this.empRec==null) {
			this.chkNullEmpRec();
		}
	}
	
	public DbRecord getEmpRecord() {
		if (this.empRec==null) {
			this.chkNullEmpRec();
		}
		return this.empRec;		
	}
	
	private void chkNullEmpRec() {
		try {			
			this.empRec = new InitialRecord(this.userPro).getDbRecord("Memployee");
			this.empRec.set("employeeid", this.getString("employeeid"));
			this.empRec.set("companyid", this.getString("companyid"));
			this.empRec.setParam("rsc_skip","true");
			this.empRec.search();
		} catch (Exception e) {
			MyLog.error(this, e);
		}
	}
	
	public void ProcessOT(){
		try {
			DbTable db = (DbTable) this.getChild("ttime_current1");			
			db.first();			
			do{				
				Ttime_current1 rec = (Ttime_current1) db.getCurrentRecordManager();	
                /* debug */
                //MyLog.debug(" !! pre process ot dateid : " + rec.getString("dateid"));
                //MyLog.debug(" !! swipe in --> " +  rec.getString("m_tm_bg"));
               // MyLog.debug(" !! swipe out --> " +  rec.getString("m_tm_en"));

				rec.PreProcessOT();
                /* debug */
                //MyLog.debug(" !! after process ot dateid : " + rec.getString("dateid"));
                //MyLog.debug(" !! swipe in --> " +  rec.getString("m_tm_bg"));
                //MyLog.debug(" !! swipe out --> " +  rec.getString("m_tm_en"));				
				db.next();
			}while(!db.eof());
		}catch(Exception e){
			MyLog.error(this,e);
		}
	}
}