//
// RMSchedulerController
//
// Created by Alonso Villanueva

@import "../AppController.j"
@import "../model/Model.j"




@implementation AutomaticPersonnel :  RMControllerObject{


  	id mode;
  
	CPPanel repoPane;
    
   	CPPanel geneRepoPane;
   	id emaiText;
   	
   	CPTableView emplTabl;
   	id emplDict;
   	id emplDictKeys;
   	id persMenu;

  	id emaiComm;
  	id repoComm;

  	
  	id checkActi;
  	id prevValuCheckActi;
  	id checkSendEmpt;
  	
  	id textDays;
  	
  	id dateStarText;
  	id dateEnddText;
	id datePickStarPane;

	id fecha0;
	id fecha1;  
	id DPSltd;

}



- (id) init:(id)paraAppCont {
	[super init];
 	
 	appCont = paraAppCont;
	dataBase = [appCont getDataBase];
	//alert("db init reports= " + [appCont getDataBase]);
	repoPane = geneRepoPane =  NULL;

	emplTabl = emplDict = NULL;
  	mode = NULL;
	prevValuCheckActi = "0";
	emaiComm = repoComm = "";
	
	if ( !mode ) {
		//mode = [appCont getModel];
		mode = [[Model alloc]init:self];
		[mode organizationCodeSet:[appCont getOrgaCode] ];
		[mode organizationIdSet:[appCont organizationId] ];
		[mode cgiSetHost:[appCont getcgiHost] server:[appCont getcgiServ]];
		[mode loadEmployeesAutomaticReport];
		emplDictKeys = [emplDict allKeys];
	}
	
	
	return self;
}




- (void)  applicationQuit {

	if ( repoPane ) {
		[repoPane orderOut:0];
		[repoPane release];
	}	
	
	if ( geneRepoPane ) {
		[geneRepoPane orderOut:0];
		[geneRepoPane release];
	}	
	
	if (emplTabl) { [emplTabl  release];}
	if (emplDict) { [emplDict  release];}
	if (emaiComm) { [emaiComm  release];}
	if (repoComm) { [repoComm  release];}
	if (mode) { 
		[mode  applicationQuit];
		[mode release];
	}

}


- (void) datePickerStartDateChange:(id)sender {
	if ( DPSltd == fecha0 ) {
		var dtx = [sender dateValue];
		[dateStarText setStringValue:[[dtx description] substringToIndex:10]];
		dtx.setFullYear(dtx.getFullYear()+3);
		[dateEnddText setStringValue:[[dtx description] substringToIndex:10]];
	}
	if ( DPSltd == fecha1 ) 
		[dateEnddText setStringValue:[[[sender dateValue] description] substringToIndex:10]];	
	[datePickStarPane close];	
}

- (void) datePickerStartPanel:(id)sender {

	DPSltd = sender;
	var lablClnd = "";

	if ( sender == fecha0 )
		lablClnd = @"Fecha Inicio";
	if ( sender == fecha1 ) 
		lablClnd = @"Fecha final";

	if ( datePickStarPane ) {
		[datePickStarPane orderFront:self];
	}else{
	
	var fram = CGRectMake(350,350,144,148);
	datePickStarPane = [[CPPanel alloc] initWithContentRect:fram styleMask:CPHUDBackgroundWindowMask|CPClosableWindowMask]; 
	[datePickStarPane setFloatingPanel:YES];
	[datePickStarPane setTitle:lablClnd];
	[datePickStarPane orderFront:self];

	var paneContView = [datePickStarPane contentView];

	fram = CGRectMake(0,0,144,148);
	var datePick = [[CPDatePicker alloc] initWithFrame:fram];
	[datePick setBackgroundColor:[CPColor whiteColor]];
	[datePick setTimeZone:[CPTimeZone defaultTimeZone]];
	[datePick setDatePickerElements:128];
	var dpe = [datePick datePickerElements];
	[datePick setDatePickerStyle:1];
	var dps = [datePick datePickerStyle];
	[datePick setDateValue:[CPDate date]];
	[datePick setObjectValue:[CPDate date]];
	[datePick setTarget:self];
	[datePick setAction:@selector(datePickerStartDateChange:)];
	//alert("dpe="+dpe+"  dps="+dps);
	
	[paneContView addSubview:datePick];
	}
}



- (void) reportsPanel {
	return repoPane;
}



- (void) reportsPanel:(id)sender {
	
	
	if (repoPane) {
		emplDict = NULL;
		[emplTabl reloadData];
		[repoPane orderFront:self];
	}else{
		
	var horiPos1 = 15;
	var horiPos2 = horiPos1 + 80;
	var horiPos3 = 310;
	var horiPos4 = horiPos3 + 245;

	var horiTextWidt = 200;
	var horiPosiOffs = -4;
	var horiPosi = 200;

	var vertPosi = 15;
	var vertPosiOffs = -4;
	var vertIncr = 26;
	var vertLineHeig = 30;

	var paneWidt = 750;
	var paneHeig = 610;
	var tablWidt = paneWidt - 20;
	var tablHeig = 150;
	
	var x = 50 + Math.random()*40;
	var y = 60 + Math.random()*40;
	var fram = CGRectMake(x,y, paneWidt,paneHeig);

	repoPane = [[CPPanel alloc] initWithContentRect:fram styleMask:CPHUDBackgroundWindowMask|CPClosableWindowMask|CPResizableWindowMask]; 
	[repoPane setFloatingPanel:YES]; 
	[repoPane orderFront:self];
	[repoPane setTitle:@"Reporte Automático Personal"];
	
	var paneContView = [repoPane contentView];
	[paneContView setBackgroundColor:coloDefaLite];
	[self addBanners:paneContView heightBlue:1. heightOrange:4.];

	var view = paneContView;


	//Tables
	
	//vertPosi += 30;
	var labe = [self addTextField:@"Empleados:" TFPosX:horiPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:view Editable:NO];
	[labe setTextColor:[CPColor whiteColor]];
	
	vertPosi += 20;

	//Pesonnel

	var fram= CGRectMake(horiPos1,vertPosi, 300,200);
	
	fram= CGRectMake(horiPos1,vertPosi, 700,300);
	var scroView= [[CPScrollView alloc] initWithFrame:fram];

	emplTabl = [[CPTableView alloc] initWithFrame:[scroView bounds]];
	[emplTabl setDataSource:self];
	[emplTabl setTarget:self];
	[emplTabl setAction:@selector(emplTableSelection:)];
	[emplTabl setAllowsColumnReordering:YES];
	[emplTabl setUsesAlternatingRowBackgroundColors:YES];
	[emplTabl setAllowsMultipleSelection:YES];
	[emplTabl setDelegate:self];

	var colu= [[CPTableColumn alloc] initWithIdentifier:@"NamePers"];
	[[colu headerView] setStringValue:@"Nombre Completo"];
	[colu setWidth:200];
	[emplTabl addTableColumn:colu];

	colu= [[CPTableColumn alloc] initWithIdentifier:@"EmaiPers"];
	[[colu headerView] setStringValue:@"Email"];
	[colu setWidth:200];
	[emplTabl addTableColumn:colu];
	
	colu= [[CPTableColumn alloc] initWithIdentifier:@"Posicion"];
	[[colu headerView] setStringValue:@"Posición"];
	[colu setWidth:200];
	[emplTabl addTableColumn:colu];
	
	colu= [[CPTableColumn alloc] initWithIdentifier:@"daysSend"];
	[[colu headerView] setStringValue:@"Dias Envio"];
	[colu setWidth:75];
	[emplTabl addTableColumn:colu];
	
	
	[scroView setDocumentView:emplTabl];
	
	/*
	//Menu Person table
	
	emplMenu = [[CPMenu alloc] initWithTitle:@"Opciones"];
	var seriCommOpti = [emplMenu insertItemWithTitle:@"Agregar Empleado" 
							    action:@selector(addFromPerson:)
							     keyEquivalent:@""
							     atIndex:0];
	
	[scroView setMenu:emplMenu];
	[[CPArray arrayWithObjects:seriCommOpti] makeObjectsPerformSelector:@selector(setTarget:) withObject:self];
	//end
	*/
	
	[view addSubview:scroView];
	
	
	vertPosi += 320;
	//start date
	labe= [self addTextField:@"Fecha Inicio:" TFPosX:horiPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:view Editable:NO];
	[labe setTextColor:[CPColor whiteColor]];
	dateStarText = [self addTextField:[[[CPDate date] description] substringToIndex:10] TFPosX:horiPos2-4 TFPosY:vertPosi-4 TFWidth:85 TFHeight:30 VView:view Editable:YES];
	fecha0 = [self addButton:@"DP" TFPosX:horiPos2 + 90 TFPosY:vertPosi-2 TFWidth:50 TFHeight:24  VView:view sizeToFit:NO Action:@selector(datePickerStartPanel:)];
	var hlpButt = [self addHelpIcon:@"/img/infoIcon.png" TFPosX:horiPos2 + 90 + 50 + 15 TFPosY:vertPosi +2 TFWidth:16 TFHeight:16 VView:view Action:@selector(dummy:)];
	[hlpButt setToolTip:@"Rango de validez de la reporteria automatica del tecnico seleccionado: ( fecha de inicio del rango )"];


	//end date
	var offSet = 90 + 50 + 10;
	vertPosi += 30;
	labe= [self addTextField:@"Fecha Final:" TFPosX:horiPos1  TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:view Editable:NO];
	[labe setTextColor:[CPColor whiteColor]];
	dateEnddText = [self addTextField:[[[CPDate date] description] substringToIndex:10] TFPosX:horiPos2-4 TFPosY:vertPosi-4 TFWidth:85 TFHeight:30 VView:view Editable:YES];
	fecha1 = [self addButton:@"DP" TFPosX:horiPos2 + 90 TFPosY:vertPosi-2 TFWidth:50 TFHeight:24  VView:view sizeToFit:NO Action:@selector(datePickerStartPanel:)];
	var hlpButt = [self addHelpIcon:@"/img/infoIcon.png" TFPosX:horiPos2 + 90 + 50 + 15 TFPosY:vertPosi +2 TFWidth:16 TFHeight:16 VView:view Action:@selector(dummy:)];
	[hlpButt setToolTip:@"Rango de validez de la reporteria automatica del tecnico seleccionado: ( fecha de inicio del rango )"];
	

	vertPosi += 40;
	//Days
	labe = [self addTextField:@"Dias envio:" TFPosX:horiPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:view Editable:NO];
	[labe setTextColor:[CPColor whiteColor]];
	//vertPosi += 20;
	textDays = [self addTextField:@"" TFPosX:horiPos2 TFPosY:vertPosi-4 TFWidth:100 TFHeight:25 VView:view Editable:YES];
    [textDays setLineBreakMode:CPLineBreakByWordWrapping]
    
	var hlpButt = [self addHelpIcon:@"/img/infoIcon.png" TFPosX:horiPos2 + 90 + 50 + 15 TFPosY:vertPosi +2 TFWidth:16 TFHeight:16 VView:view Action:@selector(dummy:)];
	[hlpButt setToolTip:@"Indica la cantidad de dias de programación en cada reporte enviado )"];
	
    vertPosi += 20;
    checkActi = [[CPCheckBox alloc] initWithFrame:CGRectMake(horiPos1,vertPosi,120,25)];
	[checkActi setTitle:"Activar"];
    [checkActi setFont:[CPFont fontWithName:@"Arial" size:12]];
    [checkActi setTextColor:[CPColor whiteColor]];
	[view addSubview:checkActi];
	
	vertPosi += 20;
	checkSendEmpt = [[CPCheckBox alloc] initWithFrame:CGRectMake(horiPos1,vertPosi,280,25)];
	[checkSendEmpt setTitle:"Enviar aunque no tenga trabajos programados"];
    [checkSendEmpt setFont:[CPFont fontWithName:@"Arial" size:12]];
    [checkSendEmpt setTextColor:[CPColor whiteColor]];
	[view addSubview:checkSendEmpt];
	
	vertPosi += 40;
	//Comment Email
	labe = [self addTextField:@"Comentario email:" TFPosX:horiPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:view Editable:NO];
	[labe setTextColor:[CPColor whiteColor]];
	vertPosi += 20;
	emaiComm = [self addTextField:@"" TFPosX:horiPos1 TFPosY:vertPosi-4 TFWidth:700 - 170 TFHeight:2.5*vertLineHeig VView:view Editable:YES];
    [emaiComm setLineBreakMode:CPLineBreakByWordWrapping];
    /*
	vertPosi += 60;
	//Comment Report
	labe = [self addTextField:@"Comentario Reporte:" TFPosX:horiPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:view Editable:NO];
	[labe setTextColor:[CPColor whiteColor]];
	vertPosi += 20;
	repoComm = [self addTextField:@" " TFPosX:horiPos1 TFPosY:vertPosi-4 TFWidth:250 TFHeight:2*vertLineHeig VView:view Editable:YES];
    [repoComm setLineBreakMode:CPLineBreakByWordWrapping];
    */
    vertPosi += 45;
    [self addButton:@"Guardar" TFPosX:horiPos4 TFPosY:vertPosi-2 TFWidth:75 TFHeight:24  VView:view sizeToFit:NO Action:@selector(updateChangesAutomaticReport:)];
    [self addButton:@"Recargar" TFPosX:(horiPos4 + 80) TFPosY:vertPosi-2 TFWidth:75 TFHeight:24  VView:view sizeToFit:NO Action:@selector(reloadEmployeeTable:)];
//    [self addButton:@"Eliminar" TFPosX:horiPos1  + 150 TFPosY:vertPosi-2 TFWidth:65 TFHeight:24  VView:view sizeToFit:NO Action:@selector(deleteChangesAutomaticReport:)];
	
	}
	
   alert ( [[CPDate date] description]);
}

- (void) reloadEmployeeTable:(id)sender {
	
	//alert("Reload")
	[emplDict removeAllObjects];
	[mode emptyEmplAutoRepoDict];
	[mode loadEmployeesAutomaticReport];
    emplDict = [mode getEmployeesArray];
    emplDictKeys = [emplDict allKeys];
	[emplTabl reloadData]
}


- (void) updateChangesAutomaticReport:(id)sender {
	
	var inde = [emplTabl selectedRow];
	if ( inde < 0 ){
		return;
	}

	
	if ([textDays stringValue] > 10 ){	
		[glblAlerPane showWithMessage:@"Atencion" info:"El numero maximo es de 10 dias"];
		return;
	}
	if ([textDays stringValue] < 0 ){	
		[glblAlerPane showWithMessage:@"Atencion" info:"El numero de dias debe ser mayor a 0"];
		return;
	}

	if ( [[dateStarText stringValue] compare:[dateEnddText stringValue]] != CPOrderedAscending ) {
		[glblAlerPane showWithMessage:@"Atencion" info:"La fecha final del rango de validez debe ser superior a la fecha inicial"];
		return;		
	}
	
	var aKey = [emplDictKeys objectAtIndex:inde];
	var objt = [emplDict objectForKey:aKey];
	
	[objt initDate: [ [dateStarText stringValue] substringToIndex:10] ];
	[objt daysToSend:[textDays stringValue] ];
	var striPara = [CPString stringWithFormat:@"nameFirst=%@:sc:nameLast=%@:sc:role=%@:sc:id=%@",[objt nameFirst],[objt nameLast],[objt role],[objt idenPers]];
	[objt contPara:striPara];
	[objt emaiList:[objt email]];
	if ([checkActi state] == 1) {
		[objt acti:"1"];
	}else{
		[objt acti:"0"];
	}
	
	if ([checkSendEmpt state] == 1) {
		[objt sendEmpt:"1"];
	}else{
		[objt sendEmpt:"0"];
	}
	
	[objt comm2: [emaiComm stringValue] ];
	var quer = "";	
	if  (  (prevValuCheckActi == "0") && ([objt acti] == "1") ){
		//console.log("need update nextGeneDate");
   		quer = [CPString stringWithFormat:@"UPDATE %@.automaticReportDefinitions SET initialDate = '%@', endDate = '%@', daysToSend = '%@', contentParameters = '%@', emailList= '%@', active = %@, sendEmpty = %@, comment2 = '%@', nextGeneDate = curdate() + interval 18 hour + interval 30 minute  WHERE identifier = '%@' AND typeReportId = 3 ",
	                         	dataBase,[objt initDate],[objt enddDate],[objt daysToSend],[objt contPara],[objt emaiList],[objt acti],[objt sendEmpt],[objt comm2],[objt idenPers] ];
	//alert (quer)
	}else{
		quer = [CPString stringWithFormat:@"UPDATE %@.automaticReportDefinitions SET initialDate = '%@', endDate = '%@', daysToSend = '%@', contentParameters = '%@', emailList= '%@', active = %@, sendEmpty = %@, comment2 = '%@'  WHERE identifier = '%@' AND typeReportId = 3 ",
	                         	dataBase,[objt initDate],[objt enddDate],[objt daysToSend],[objt contPara],[objt emaiList],[objt acti],[objt sendEmpt],[objt comm2],[objt idenPers] ];
	   // console.log("just update ");
	}
	 [self query:quer];
	 [emplDict setObject:objt forKey:aKey];
	 [emplTabl reloadData];

}


//- (void) deleteChangesAutomaticReport:(id)sender {}


- (void) dummy:(id)sender {
   // No hace nada
}



- (void) emplTableSelection:(id)sender {
	var inde = [emplTabl selectedRow];
	if ( inde < 0 ){
		return;
	}
	
	var aKey = [emplDictKeys objectAtIndex:inde];
	var objt = [emplDict objectForKey:aKey];
	
	[textDays setStringValue: [objt daysToSend]];
	var a =  [objt initDate];
	[dateStarText setStringValue: [objt initDate]];
	[dateEnddText setStringValue: [objt enddDate]];
	var tempStri = [[dateStarText stringValue] substringToIndex:10];
	[dateStarText setStringValue: tempStri];
	var tempStri = [[dateEnddText stringValue] substringToIndex:10];
	[dateEnddText setStringValue: tempStri];
//	[[dateStarText stringValue] substringToIndex:10];
	if ([objt acti] == 1) {
		[checkActi setStringValue:"1"];
		prevValuCheckActi = "1";
	}else{
		[checkActi setStringValue:"0"];
		prevValuCheckActi = "0";
	}
	 
	if ([objt sendEmpt] == 1) {
		[checkSendEmpt setStringValue:"1"];
	}else{
		[checkSendEmpt setStringValue:"0"];
	}
	
	[emaiComm setStringValue: [objt comm2]];
}


//		TABLE SOURCE DELEGATE METHODS

- (int) numberOfRowsInTableView:(CPTableView)tablView {
	var coun= 0;
	var quer;
	
	if ( tablView == emplTabl ) {
		emplDict = [mode getEmployeesArray];
		emplDictKeys = [emplDict allKeys];
		coun = [emplDict count];
	}
	

	return coun;
}


- (id) tableView:(CPTableView)tablView objectValueForTableColumn:(CPTableColumn)tablColu row:(int)rowInde {

	var headStri= [[tablColu headerView] stringValue];
	var headIden= [tablColu identifier];
	var valu = @"N/A";
	emplDictKeys = [emplDict allKeys];


	if ( tablView == emplTabl ) {
		var aKey = [emplDictKeys objectAtIndex:rowInde];
		var objt = [emplDict objectForKey:aKey];
		if ( [headIden isEqualToString:@"NamePers"] ){
			valu = [objt nameLast] + " " + [objt nameFirst];
		}else if ( [headIden isEqualToString:@"EmaiPers"] ){
			valu = [objt email] ;	
		}else if ( [headIden isEqualToString:@"Posicion"] ){
			valu = [objt role] ;
		}
		else if ( [headIden isEqualToString:@"daysSend"] ){
			valu = [objt daysToSend] ;			
		}
	}

		
	return valu;
}









@end
