
// AppController.j
// RMSchedulerController
//
// Created by Alonso Villanueva

@import <Foundation/Foundation.j>
@import <AppKit/AppKit.j>
@import <MapKit/MKMapView.j>
@import <AppKit/CPTextField.j>
@import <AppKit/CPApplication.j>
@import <Foundation/CPURLRequest.j>
@import "AppController.j"




// var appCont; //comment 2017-03-03





@implementation RMSchedulerUserController : RMControllerObject {


	CPPanel userPane;
	CPTable userTabl;
	
	id userArra;
	id userText;
	id passText;
	id nameText;


}



- (id) init:(id)paraAppCont {
	[super init];
 	
 	appCont = paraAppCont;
	dataBase = [appCont getDataBase];
	userPane = NULL;
	userArra = NULL;
	userText = NULL;
	passText = NULL;
	nameText = NULL;


	return self;
}




- (void)  applicationQuit {

	if ( userPane ) {
		[userPane orderOut:0];
		[userPane release];
	}
	if (userText) { [userText release];}
	if (passText) { [passText  release];}
	if (userArra) { [userArra  release];}
	if (nameText) { [nameText  release];}
	
}


- (void) createTemporaryTable:(id)sender{

	//Create Temporary table that gonna be use in the calendar
	console.log("CREANDO LA TABLA TEMPORAL");
	var userName = [userText  stringValue];
	var useTabl = "tbl_"+userName + "Event";
	console.log("USETABL = " + useTabl );
	var quer = "CREATE TABLE IF NOT EXISTS `"+useTabl+"` (";
    quer +="`id` int(11) NOT NULL DEFAULT '0',";
  	quer +="`seriesId` bigint DEFAULT NULL,";
  	quer +="`eventIdentifier` varchar(64) CHARACTER SET utf8 DEFAULT NULL,";
  	quer +="`start_date` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,";
  	quer +="`end_date` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,";
  	quer +="`text` varchar(256) COLLATE utf8_unicode_ci DEFAULT NULL,";
  	quer +="`source` varchar(128) CHARACTER SET utf8 DEFAULT NULL,";
  	quer +="`calendar` varchar(1024) COLLATE utf8_unicode_ci DEFAULT NULL,";
  	quer +="`personnel` varchar(1024) COLLATE utf8_unicode_ci DEFAULT NULL,";
  	quer +="`location` varchar(256) CHARACTER SET utf8 DEFAULT NULL,";
  	quer +="`customer` varchar(64) CHARACTER SET utf8 DEFAULT NULL,";
  	quer +="`billing` varchar(32) CHARACTER SET utf8 DEFAULT NULL,";
  	quer +="`type` varchar(128) COLLATE utf8_unicode_ci DEFAULT NULL,";
  	quer +="`lat` double DEFAULT NULL,";
  	quer +="`lng` double DEFAULT NULL,";
  	quer +="`vehicle` varchar(64) CHARACTER SET utf8 DEFAULT NULL,";
  	quer +="`color` varchar(32) CHARACTER SET utf8 DEFAULT NULL,";
  	quer +="`notes` varchar(256) CHARACTER SET utf8 DEFAULT NULL,";
  	quer +="`eventComm` text COLLATE utf8_unicode_ci,";
  	quer +="`serieComm` text COLLATE utf8_unicode_ci,";
  	quer +="UNIQUE KEY `events_id` (`id`)";
	quer +=")ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
	console.log(quer);
	[self query: quer newCgiServ:@"rm_execute_define"];
	
	quer = "CREATE TRIGGER updateEventsPermanent"+useTabl+" BEFORE UPDATE ON `"+useTabl+"` ";
	quer +="FOR EACH ROW ";
	quer +="BEGIN ";
		quer +="UPDATE rmscheduler_orkincr.eventsPermanent "; 
    	quer +="SET ";
        	quer +="calendar 		  = NEW.calendar,";
        	quer +="personnel	  = NEW.personnel,";
        	quer +="vehicle			  = NEW.vehicle,";
        	quer +="start_date      = NEW.start_date,";
			quer +="end_date       = NEW.end_date,";        
        	quer +="eventComm   = NEW.eventComm";
			quer +=" WHERE ";
        	quer +="id = NEW.id;";
	quer +=" END;";
	[self query: quer newCgiServ:@"rm_execute_define"];
	//console.log(quer);
	
	quer = "CREATE TRIGGER updateSerieCommEventsPerm"+useTabl+" BEFORE UPDATE ON `"+useTabl+"` ";
	quer += "FOR EACH ROW ";
    quer +="BEGIN ";
	quer +="UPDATE rmscheduler_orkincr.eventsPermanent ";
    	quer +="SET ";
        quer +="serieComm  = NEW.serieComm ";
		quer +="WHERE ";
        quer +="seriesId = NEW.seriesId; ";
	quer +="END;";
	[self query: quer newCgiServ:@"rm_execute_define"];
	//console.log(quer);
	quer = "CREATE TRIGGER deleteEventsPermanent"+useTabl+" AFTER DELETE ON `"+useTabl+"` ";
	quer +="FOR EACH ROW ";
	quer +="BEGIN ";
		quer +="DELETE FROM rmscheduler_orkincr.eventsPermanent  ";
   		quer +="WHERE ";
    	quer +="eventsPermanent.id = OLD.id; ";    
	quer +="END;";
	[self query: quer newCgiServ:@"rm_execute_define"];
}

- (void) dropTemporaryTable:(id)sender{
	var userName = [userText  stringValue];
	var useTabl = "tbl_"+userName + "Event";
	var quer = "DROP TABLE`"+useTabl+"`;";
	[self query: quer newCgiServ:@"rm_execute_define"];
}

- (void) reportsPanel {
	return userPane;
}


- (void) reportsPanel:(id)sender {

	var horiPos1 = 10;
	var horiPos2 = horiPos1 + 100;
	var horiPos3 = 390;
	var horiPos4 = horiPos3 + 100;

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

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

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

	userPane = [[CPPanel alloc] initWithContentRect:fram styleMask:CPHUDBackgroundWindowMask|CPClosableWindowMask|CPResizableWindowMask]; 
	[userPane setFloatingPanel:YES]; 
	[userPane orderFront:self];
	[userPane setTitle:@"Usuarios"];
	
	var paneContView = [userPane contentView];
	[paneContView setBackgroundColor:coloDefaLite];

	var view = paneContView;
	
	vertPosi = 20;

	var fram= CGRectMake(horiPos2,vertPosi, 450,tablHeig);
	var scroView= [[CPScrollView alloc] initWithFrame:fram];

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

	colu = [[CPTableColumn alloc] initWithIdentifier:@"Nombre"];
	[[colu headerView] setStringValue:@"Nombre"];
	[colu setWidth:140];
	[userTabl addTableColumn:colu];

	colu = [[CPTableColumn alloc] initWithIdentifier:@"Usuario"];
	[[colu headerView] setStringValue:@"Usuario"];
	[colu setWidth:140];
	[userTabl addTableColumn:colu];

	colu = [[CPTableColumn alloc] initWithIdentifier:@"Contraseña"];
	[[colu headerView] setStringValue:@"Contraseña"];
	[colu setWidth:140];
	[userTabl addTableColumn:colu];

	[scroView setDocumentView:userTabl];

	[view addSubview:scroView];


    vertPosi += tablHeig + 10;
    vertPosiHere = vertPosi;

	labe = [self addTextField:@"Nombre:" TFPosX:horiPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:view Editable:NO];
	[labe setTextColor:[CPColor whiteColor]];

	nameText = [self addTextField:@"" TFPosX:horiPos2 TFPosY:vertPosi-4 TFWidth:140 TFHeight:vertLineHeig VView:view Editable:YES];

    vertPosi += vertIncr;

	labe = [self addTextField:@"Usuario:" TFPosX:horiPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:view Editable:NO];
	[labe setTextColor:[CPColor whiteColor]];

	userText = [self addTextField:@"" TFPosX:horiPos2 TFPosY:vertPosi-4 TFWidth:140 TFHeight:vertLineHeig VView:view Editable:YES];

    vertPosi += vertIncr;

	labe = [self addTextField:@"Contraseña:" TFPosX:horiPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:view Editable:NO];
	[labe setTextColor:[CPColor whiteColor]];

	passText = [self addTextField:@"" TFPosX:horiPos2 TFPosY:vertPosi-4 TFWidth:140 TFHeight:vertLineHeig VView:view Editable:YES];

    vertPosi += vertIncr +vertLineHeig;


    var butt = [[CPButton alloc] initWithFrame: CGRectMake(horiPos2,vertPosi, 75,24)];
	[butt setTitle:"Ingresar"];
	[butt setTarget:self];
	[butt setAction:@selector(userInsert:)];                
	[view addSubview:butt];

	butt = [[CPButton alloc] initWithFrame: CGRectMake(horiPos2+75,vertPosi, 75,24)];
	[butt setTitle:"Eliminar"];
	[butt setTarget:self];
	[butt setAction:@selector(userDelete:)];                
	[view addSubview:butt];

	butt = [[CPButton alloc] initWithFrame: CGRectMake(horiPos2+150,vertPosi, 75,24)];
	[butt setTitle:"Limpiar"];
	[butt setTarget:self];
	[butt setAction:@selector(userClearFields:)];                
	[view addSubview:butt];
}

- (void) userClearFields:(id)sender {
	[nameText setStringValue:@""];
	[userText setStringValue:@""];
	[passText setStringValue:@""];
}

- (void) userInsert:(id)sender {
	var userNameFull = [nameText  stringValue];
	var userName = [userText  stringValue];
	var userPass = [passText  stringValue];
	var quer = "Select idUser from riglobal.user where name = '"+userName+"';"
	var arraAux = [self query:quer];
	if ( [arraAux count] > 0 ) {
    	[glblAlerPane showWithMessage:@"Atención" info:"Ese nombre de usuario no esta disponible."];
      	return; 
    }
	quer = [CPString stringWithFormat:@"insert into riglobal.user (fullname,name,password,fkRoleId,fkClientId,fkProduct,fkLanguage) values ('%@','%@','%@',1,1,1,1)",
		userNameFull,userName,userPass];
	[self query:quer];
	[self createTemporaryTable: self];
	[self userClearFields:self];
	[userTabl reloadData];
	[glblAlerPane showWithMessage:@"Insertado" info:@"Usuario ingresado correctamente."];
	
}

- (void) userDelete:(id)sender {
	var inde = [userTabl selectedRow];
	if ( inde < 0 )
		return;
	var id = [[userArra[inde] valueList] objectAtIndex:0];
	var user = [[userArra[inde] valueList] objectAtIndex:1];
	var conf = confirm("Quiere eliminar el usuario "+user+"?");
	if ( ! conf )
		return;

	var quer = [CPString stringWithFormat:@"delete from riglobal.user where idUser=%@",id];
	[self query:quer];

	[userTabl reloadData];
	[self dropTemporaryTable: self];
	[glblAlerPane showWithMessage:@"Eliminado" info:@"Usuario eliminado correctamente."];
}


- (void) userTableSelection:(id)sender {
	var inde = [userTabl selectedRow];
	if ( inde < 0 )
		return;

	var valuList = [userArra[inde] valueList];
	var userNameFull = [valuList objectAtIndex:1];
	var userName = [valuList objectAtIndex:2];
	var userPass = [valuList objectAtIndex:3];
	
	[nameText setStringValue:userNameFull];
	[userText setStringValue:userName];
	[passText setStringValue:userPass];
}

- (int) numberOfRowsInTableView:(CPTableView)tablView {
	var coun= 0;
	var quer;
	quer = [CPString stringWithFormat:@"SELECT idUser,fullname,name,password  FROM riglobal.user WHERE fkRoleId = 1;"];
	userArra = [self query:quer];
	coun= [userArra 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";

		var arra = [[userArra objectAtIndex:rowInde] valueList];
		if ( [headStri isEqualToString:@"Nombre"] )
			valu= arra[1];
		else if ( [headStri isEqualToString:@"Usuario"] )
			valu= arra[2];
		else if ( [headStri isEqualToString:@"Contraseña"] )
			valu= arra[3];

	return valu;
}

@end
