package com.csc.library.databean;

import com.csc.library.utilities.MyLog;
import com.csc.library.utilities.UProfile;

import java.rmi.RemoteException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Hashtable;

import std.library.DataTable;
import std.library.TimeSpan;

import com.csc.library.database.CscConnection;
import com.csc.library.database.FieldManager;
import com.csc.library.database.StaticConfig;
import com.csc.library.database.StaticProperties;
import com.csc.library.session.DbInquiry;
import com.csc.library.session.DbRecord;
import com.csc.library.session.InitialInquiry;
import com.csc.library.session.InitialRecord;
import com.csc.library.session.RecordCmp;
import com.csc.library.timeattendance.TimeZone;
import com.csc.library.timeinterface.AdjustTime;
import com.csc.library.utilities.CscCalendar;
import com.csc.library.utility.NAdjustTime;

/*
 * ��㹡���红����š�û�Ѻ��ا���ҡ�÷ӧҹ
 * ����Ҩҡ�͡��õ�ҧ � �� ��� 㺢��ͷ� �����¹�� ��š��
 */
public class Tadjtime0 extends RecordCmp implements AdjustTime {

	private boolean flag = false;
	private DbInquiry inqTime = null;

	public Tadjtime0() {
		super("Tadjtime0", "Tadjtime0 Table");
	}

	public CscCalendar getDocDate() {
		CscCalendar csc = new CscCalendar(this.getString("docdate"));
		return csc;
	}

	public String getUpdateType() {
		return this.getString("updtype");
	}

	public String getDocNo() {
		return this.getString("docid");
	}

	public String getDocType() {
		return this.getString("doctype");
	}

	public String getTime0() {
		return this.getString("time0id");
	}

	public String getEventGroup() {
		return this.getString("eventgrp");
	}

	public String getOldTime0() {
		return this.getString("oldtime0id");
	}

	public String getOldEventGroup() {
		return this.getString("oldeventgrp");
	}

	public String get_LV_TY() {
		return this.getString("lv_ty");
	}

	public float get_LV() {
		return Float.valueOf(this.getString("lv")).floatValue();
	}

	public String get_TR_Type() {
		return this.getString("tr_type");
	}

	public CscCalendar get_DT_BG() {
		CscCalendar csc = new CscCalendar(this.getString("dt_bg"));
		try {
			csc.setCSCTime(this.get_TM_BG());
		} catch (Exception e) {
			MyLog.error(this, e);
		}
		return csc;
	}

	public CscCalendar get_DT_EN() {
		CscCalendar csc = new CscCalendar(this.getString("dt_en"));
		try {
			csc.setCSCTime(this.get_TM_EN());
		} catch (Exception e) {
			MyLog.error(this, e);
		}
		return csc;
	}

	public float get_TM_BG() {
		return Float.valueOf(this.getString("tm_bg")).floatValue();
	}

	public float get_TM_EN() {
		return Float.valueOf(this.getString("tm_en")).floatValue();
	}

	public String getString_TM_BG() {
		return this.getString("tm_bg");
	}

	public String getString_TM_EN() {
		return this.getString("tm_en");
	}

	public CscCalendar getAdjDate() {
		return new CscCalendar(this.getString("docdate"));
	}
	
	public String getAppStatus(){
		return this.getString("status");
	}

	public TimeZone getTimeWork() {
		TimeZone timeWork = null;
		try {
			CscCalendar csc = new CscCalendar(this.getString("docdate"));
			// CscCalendar csc = new CscCalendar(this.getString("dt_bg"));
			if (this.inqTime == null) {
				this.inqTime = new InitialInquiry(this.userPro).getDbInquiry();
				this.inqTime.setParam(this.param);
				this.inqTime.setSchemaName(this.userPro.getSchemaName());
				this.inqTime.initMyTable("Mtime1", "", "");
				this.inqTime.setColumn("*");
			}
			this.inqTime.setFilter("time0id='" + this.getString("time0id")
					+ "' and dayweekid='" + csc.getCSCDOW() + "'");
			this.inqTime.refresh();
			while (this.inqTime.next()) {
				DbRecord rec = this.inqTime.getCurrentDbRecord();
				CscCalendar timeIN = new CscCalendar(csc.getDDMMYYYY());
				timeIN.setCSCTime(rec.getFloat("timein1"));

				CscCalendar timeOUT = new CscCalendar(csc.getDDMMYYYY());
				timeOUT.setCSCTime(rec.getFloat("timeout2"));
				if (rec.getFloat("timeout2") < rec.getFloat("timein1")) {
					timeOUT.incDate();
				}
				timeWork = new TimeZone(timeIN, timeOUT);
			}
		} catch (Exception e) {
			MyLog.error(this, e);
		}
		return timeWork;
	}

	public TimeZone getTimeBreak() {
		TimeZone timeBreak = null;
		try {
			CscCalendar csc = new CscCalendar(this.getString("docdate"));
			// CscCalendar csc = new CscCalendar(this.getString("dt_bg"));
			if (this.inqTime == null) {
				this.inqTime = new InitialInquiry(this.userPro).getDbInquiry();
				this.inqTime.setParam(this.param);
				this.inqTime.setSchemaName(this.userPro.getSchemaName());
				this.inqTime.initMyTable("Mtime1", "", "");
				this.inqTime.setColumn("*");
			}
			this.inqTime.setFilter("time0id='" + this.getString("time0id")
					+ "' and dayweekid='" + csc.getCSCDOW() + "'");
			this.inqTime.refresh();
			while (this.inqTime.next()) {
				DbRecord rec = this.inqTime.getCurrentDbRecord();
				CscCalendar breakIN = new CscCalendar(csc.getDDMMYYYY());
				breakIN.setCSCTime(rec.getFloat("timeout1"));
				if (rec.getFloat("timeout1") < rec.getFloat("timein1")) {
					breakIN.incDate();
				}
				CscCalendar breakOUT = new CscCalendar(csc.getDDMMYYYY());
				breakOUT.setCSCTime(rec.getFloat("timein2"));
				if (rec.getFloat("timein2") < rec.getFloat("timein1")) {
					breakOUT.incDate();
				}

				/*
				 * if (breakIN.getCSCTime()>breakOUT.getCSCTime()) {
				 * breakOUT.incDate(); }
				 */
				// timeBreak.setTimeZone(breakIN, breakOUT);
				timeBreak = new TimeZone(breakIN, breakOUT);
			}
		} catch (Exception e) {
			MyLog.error(this, e);
			// TODO Auto-generated catch block
		}
		return timeBreak;
	}

	public String getStatus() {
		return this.getString("status");
	}

	public String getAdjustTemp() {
		return this.getString("adjusttemp");
	}

	private boolean deleteOldLeave(String type) {
		boolean result = false;
		int count = 0, del = 0;
		try {
			String filter = "";
			if (type.equals("T")) {
				filter = "employeeid='" + this.getString("employeeid")
						+ "' and docid='" + this.getString("docid") + "' "
						+ " and doctype='" + this.getString("doctype")
						+ "' and dateid='" + this.getString("docdate") + "' ";
			} else if (type.equals("P")) {
				filter = "employeeid='" + this.pRemote.getString("employeeid")
						+ "' and docid='" + this.pRemote.getString("docno")
						+ "' " + " and doctype='"
						+ this.pRemote.getString("doctype") + "' and dateid='"
						+ this.pRemote.getString("dateid") + "' ";
			}
			DbInquiry inq = new InitialInquiry(this.userPro).getDbInquiry();
			inq.initMyTable("Tleave_summary", filter, "");
			inq.setColumn("*");
			inq.refresh();
			while (inq.next()) {
				DbRecord rec = inq.getCurrentDbRecord().cloneRecord(true);
				if (rec.getString("table_name").equalsIgnoreCase("TADJTIME0")) {
					rec.delete();
					del++;
				} else {
					return false;
				}
				count++;
			}

			if (count == 0 || del > 0) {
				result = true;
			}
		} catch (Exception e) {
			MyLog.error(this, e);
		}
		return result;
	}

	private void saveLeave() {
		try {
			DbRecord rec = new InitialRecord(this.userPro).getDbRecord("Tleave_summary");
			rec.set("DOCID", this.getString("docid"));
			rec.set("DOCTYPE", this.getString("doctype"));
			rec.set("DATEID", this.getString("docdate"));
			rec.set("EMPLOYEEID", this.getString("employeeid"));
			rec.set("TABLE_NAME", "TADJTIME0");
			//================== Nuiss Code =================
			/**
			 * Author : Nuiss
			 * Date : 11/11/2552
			 * Logic : ��. �� ��ͧ�����ҡѺ 0 
			 */
			double lvHour =this.getDouble("lv");
			if(lvHour<=0.00){
				lvHour = this.getLeaveHourFromTadjtime0();			 
				System.out.print("==================Nuiss Debug==================" 
						+"\n Critical Error ! leave hour is : 0 at employeeid = "+ this.getString("employeeid")
						+"\n dateid = " +this.getString("docdate") 
						+"\n docid = " +this.getString("docid")
						+"\n set M_LV =  "+lvHour
						+"\n with leave hour from Tadjtime0 is: " +lvHour
						+"==================Nuiss Debug==================");
			}//end if 
			rec.set("M_LV", lvHour);
			//================== Nuiss Code =================
			rec.set("LV_TYPE", this.getString("lv_ty"));
			rec.set("LV_BG_DATE", this.getString("dt_bg"));
			rec.set("LV_EN_DATE", this.getString("dt_en"));
			rec.set("LV_BG_TIME", this.getDouble("tm_bg"));
			rec.set("LV_EN_TIME", this.getDouble("tm_en"));
			rec.set("HOUR_S", this.getDouble("hour_s"));
			rec.set("BU1", this.getString("bu1"));
			rec.set("BU2", this.getString("bu2"));
			rec.set("BU3", this.getString("bu3"));
			rec.set("BU4", this.getString("bu4"));
			rec.set("BU5", this.getString("bu5"));
			rec.set("BRANCH", this.getString("branch"));
			rec.set("EMP_POSITION", this.getString("emp_position"));
			rec.set("EMP_GROUP", this.getString("emp_group"));
			rec.set("JOBCODE", this.getString("jobcode"));
			rec.set("COSTCENTER", this.getString("costcenter"));
			rec.set("SALATYPE", this.getString("salatype"));
			rec.save();
		} catch (Exception e) {
			MyLog.error(this, e);
		}
	}

	protected boolean preInsertTrigger() throws Exception {
		boolean result = super.preInsertTrigger();
		// this.setEmployeeDetail();
		return result;
	}

	protected boolean preUpdateTrigger() throws Exception {
		boolean result = super.preUpdateTrigger();
		// this.setEmployeeDetail();
		if (pRemote.getString("updtype").equals("A")) {
			try {
				// ź������㹡���� Transaction
				this.flag = this.deleteOldLeave("P");
			} catch (Exception e) {
				MyLog.error(this, e);
			}
		}
		return result;
	}

	protected void postDeleteTrigger() throws Exception {
		super.postDeleteTrigger();
		if (this.getUpdateType().equals("A")) {
			try {
				// ź������㹡���� Transaction
				this.deleteOldLeave("T");
			} catch (Exception e) {
				MyLog.error(this, e);
			}//end try 
		}//end if 
	}//end method postDeleteTrigger

	protected void postInsertTrigger() throws Exception {
		super.postInsertTrigger();
		if (this.getUpdateType().equals("A") || this.getUpdateType().equals("O")) {
			try {
				/* 'B','OM','O' ���㺢��ͷ� �����繵�ͧ��ŧ�ʹ���� */
				if(!(this.getString("DOCTYPE").equalsIgnoreCase("B") 
						|| this.getString("DOCTYPE").equalsIgnoreCase("O")
						|| this.getString("DOCTYPE").equalsIgnoreCase("OM"))){
					
					if (this.deleteOldLeave("T")) {
						this.saveLeave();			
					}//end if 
				}
			} catch (Exception e) {
				MyLog.error(this, e);
			}//end try
		}//end if 
	}//end method postInsertTrigger

	
	protected void postUpdateTrigger() throws Exception {
		super.postUpdateTrigger();
		if (this.getUpdateType().equals("A") || this.getUpdateType().equals("O")) {
			try {
				/* 'B','OM','O' ���㺢��ͷ� �����繵�ͧ��ŧ�ʹ���� */
				if(!(this.getString("DOCTYPE").equalsIgnoreCase("B") 
						|| this.getString("DOCTYPE").equalsIgnoreCase("O")
						|| this.getString("DOCTYPE").equalsIgnoreCase("OM"))){
					if (this.flag) {
						this.saveLeave();
					}//end if 
				}
			} catch (Exception e) {
				MyLog.error(this, e);
			}//end try
		}//end if 
	}//end method postUpdateTrigger

	private void setEmployeeDetail() {
		try {
			DbInquiry inq = new InitialInquiry(this.userPro).getDbInquiry();
			inq.setParam(this.param);
			inq.setSchemaName(this.userPro.getSchemaName());
			inq.initMyTable("Memployee", "employeeid='"
					+ this.getString("employeeid") + "'", "");
			inq
					.setColumn("employeeid, companyid, bu1, bu2, bu3, bu4, bu5, branch, "
							+ "job, emp_position, emp_group, bossid, salatype, workarea");
			inq.refresh();
			while (inq.next()) {
				DbRecord rec = inq.getCurrentDbRecord();
				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("job", rec.getString("job"));
				this.set("emp_position", rec.getString("emp_position"));
				this.set("emp_group", rec.getString("emp_group"));
				this.set("branch", rec.getString("branch"));
				this.set("bossid", rec.getString("bossid"));
				this.set("salatype", rec.getString("salatype"));
				this.set("workarea", rec.getString("workarea"));
			}
		} catch (Exception e) {
			MyLog.error(this, e);
		}
	}

	public String getWorkarea() {
		return this.getString("ot_workarea");
	}

	public String getSalatype() {
		return this.getString("ot_salatype");
	}

	public String getOT_type() {
		return this.getString("ot_type");
	}

	public String getOT_time0() {
		return this.getString("ot_time0");
	}

	public float getHour_s() {
		return this.getFloat("hour_s");
	}

	public String getDocStatus() {
		return this.getString("wf_status");
	}
	
	/**
	 * Author : Nuiss
	 * Date : 12/11/2552
	 * Logic : �� ��. �� �ҡ table tadjtime0
	 * @return
	 */
	private double getLeaveHourFromTadjtime0() throws SQLException{
		CscConnection conn = null;
		Statement stmt =null;
		ResultSet resultSet = null;
		double leaveHour = 0.0d;
		
		String sqlQuery = " select employeeid,docid,lv from tadjtime0 where updtype='A' "+
		" and employeeid ='"+this.getString("employeeid")+"' "+
		" and docdate ='"+this.getString("docdate")+"' "+
		" and dt_bg = '"+this.getString("dt_bg")+"' and tm_bg = "+this.getString("tm_bg")+
		" and dt_en = '"+this.getString("dt_en")+"' and tm_en = "+this.getString("tm_en")+
		" and docid = '"+this.getString("docid")+"' ";
		try{
			conn = (CscConnection) StaticProperties.myConnection.getConnection(this.userPro.get("dbname"));
			stmt = conn.createStatement();
			resultSet = stmt.executeQuery(sqlQuery);
			while(resultSet.next()){
				leaveHour = Double.valueOf(resultSet.getString("LV"));
			}//end while
		}catch(Exception ex){
			System.out.print("Error in Tadjtime0.getLeaveHourFromTadjtime0()...");
		}finally{
			resultSet.close();
			if(stmt!=null){
				stmt.close();
			}
			conn.close();
		}//end try
		return leaveHour;
	}//end method getLeaveHourFromTadjtime0
}//end class