@import <MapKit/MKMapView.j>
@import <MapKit/MKLocation.j>
@import "RMControllerObject.j"
@import "trackingObject.j"


@implementation PSTrackingMap:RMControllerObject {  //RMControllerObject{

      id               myApp;                // back reference to AppController
      id               dynaDocu;
      id               lngt;
      id               lttd;
      id               posi;
      id               locCent;
      id               windMapp;
      id               myMap;
      id               myMapView;
      id               count;

      id               mobiPopu;
      id               refrButt;

      id               database;

      CPDictionary     trckObjs   @accessors;
      CPDictionary     hashObjs   @accessors;
      id               inClause;

}



- (id) action_buttons:(id)sender {
	if ( sender == refrButt ) {
		[refrButt setEnabled:0];
		[self refreshTracking];
		[refrButt setEnabled:1];
	}
	else if ( sender == mobiPopu ) {
		var sltdAlia = [mobiPopu titleOfSelectedItem];
		var sltdIndx = [hashObjs objectForKey:sltdAlia];
		var sltdObje = [trckObjs objectForKey:sltdIndx];
		var posi     = new google.maps.LatLng( [sltdObje lastPoin].y, [sltdObje lastPoin].x );
        myMap.setCenter(posi);
        myMap.setZoom(16);
	}
}



- (id) addPopupButtonMap:(CPString)aString TFPosX:(int)aXcoord TFPosY:(int)aYcoord TFWidth:(int)aWidth TFHeight:(int)aHeight VView:(CPView)aView pullsDown:(BOOL)pullDown {
	var PopUpButton = [[CPPopUpButton alloc] initWithFrame:CGRectMake(aXcoord, aYcoord,aWidth,aHeight) pullsDown:pullDown]; 
	[PopUpButton setTitle:aString];
	[PopUpButton setTarget:self];
	[aView addSubview:PopUpButton]; 
	return PopUpButton;
}



- (id) getButtonMap:(CPRect)aFrame VView:(CPView)aView sizeToFit:(BOOL)Size2Fit Action:(SEL)anAction Target:(id)trgt Title:(CPString)aString icon:(CPString)_imagPath {
	var Button = [[CPButton alloc] initWithFrame:aFrame];
    [Button setTitle:aString];   //[langDict translationOf:aString]];

	if ( Size2Fit ) {
		[Button sizeToFit];
	}
	[Button setAction:anAction];
	[Button setTarget:trgt];
	[aView addSubview:Button];

	if ( [_imagPath length] > 1 ) {
		var imag = [[CPImage alloc] initWithContentsOfFile:_imagPath];
    	[Button setImage:imag];
		[Button setImagePosition:CPImageLeft];
	}
	return Button;
}



- (void) buildTheWindow {
    posi     = new google.maps.LatLng(lttd, lngt);
    locCent  = [[MKLocation alloc] initWithLatitude:[lttd floatValue]  andLongitude:[lngt floatValue]];
    windMapp = [[CPWindow alloc] initWithContentRect:CGRectMake(600,60,600,620) styleMask:CPClosableWindowMask|CPTitledWindowMask|CPResizableWindowMask];

	[windMapp setDelegate:self];
	[windMapp setAcceptsMouseMovedEvents:NO];
	[windMapp makeKeyAndOrderFront:self];
	[windMapp setTitle:"Mapa"];
	windMappContView = [windMapp contentView];
	[windMappContView setBackgroundColor:[CPColor colorWithRed:70./255. green:80.0/255.0 blue:90.0/255.0 alpha:1.0]];
	myMapView = [[MKMapView alloc] initWithFrame:CGRectMake(4, 30, 590, 580 ) apiKey:'AIzaSyCRoA5SknDayXD8Rs44vui4TQSdqhfVTF0' center:locCent];

	[windMapp setMinSize:CGSizeMake(500,500)];
	[myMapView setAutoresizingMask:CPViewHeightSizable | CPViewWidthSizable];
	[myMapView setDelegate:myMapView];
	[windMappContView addSubview:myMapView];
	[myMapView setESSDele:self];

}



- (void) createObjectsDictionary {
	trckObjs         = [[CPDictionary alloc] init];
	hashObjs         = [[CPDictionary alloc] init];
	inClause         = "(";
	var sepa         = "";
	var quer         = "SELECT a.*,IFNULL(\"Blue\",b.attributeValue),c.ObjectIMEI,d.iddevice FROM " + database + ".securityObjectTable as a INNER JOIN ";
	quer            += database + ".attributes as b ON a.ObjectName=b.ObjectName AND b.attributeName=\"objectColor\" ";
	quer            += "INNER JOIN " + database + ".devices as c ON a.ObjectName=c.ObjectName ";
	quer            += "INNER JOIN avldata.device as d ON c.ObjectIMEI=d.IMEI";

	var arraAux      = [self query:quer newCgiServ:@"rm_execute_base64_b14_2"];
	
 	for ( var i  = 0; i < [arraAux count]; i++ ) {
 		var valu = [[arraAux objectAtIndex:i] valueList];
 		var trckObje = [[trackingObject alloc] initWithRecord:valu inMap:myMap];
 		[trckObjs setObject:trckObje forKey:[trckObje idDevice]];   
 		[hashObjs setObject:[trckObje idDevice] forKey:[trckObje objeAlia]];
 		if ( i > 0 )
 			sepa = ",";
 		inClause    += sepa + [trckObje idDevice];
 		var alia     = [trckObje objeAlia];
 		[mobiPopu addItemWithTitle:alia];
 	}
 	inClause += ")";
}



- (void) findBaseCoordinates {

	var quer         = "SELECT attributeValue,attributeName FROM " + database + ".attributes WHERE attributeName in (\"baseLong\",\"baseLati\")";
	var arraAux      = [self query:quer newCgiServ:@"rm_execute_base64_b14_2"];

 	for ( var i  = 0; i < [arraAux count]; i++ ) {
		var valu = [[arraAux objectAtIndex:i] valueList];
		if ( [valu[1] isEqualToString:@"baseLong"] ) {
			lngt = [valu[0] floatValue];
		}
		else if ( [valu[1] isEqualToString:@"baseLati"] ) {
			lttd = [valu[0] floatValue];
		}
	}

}



- (id) init {
    self = [super init];
    if ( self ) {
    	count	 = 0;
    	lngt 	 = -86.275;
	    lttd  	 = 11.2;
	    database = @"ricore_orkincr";
    	[self findBaseCoordinates];
    	[self createObjectsDictionary];
    	[self buildTheWindow];
    }
	return self;
}



- (void) refreshTracking {
	var quer         = "SELECT idDevice,DATE_ADD(date, INTERVAL -6 HOUR) as fecha,longitude,latitude,stoppeddate,movingstatus FROM avldata.transactionslast Where idDevice IN " + inClause;
	var arraAux      = [self query:quer newCgiServ:@"rm_execute_base64_b14_2"];
	for ( var i = 0; i < [arraAux count]; i++ ) {
		var valu = [[arraAux objectAtIndex:i] valueList];
		var indx = valu[0];
		var obje = [trckObjs objectForKey:indx];
		[obje declareMap:myMap];
		//[obje addLastPoint:valu[1] :valu[2] :valu[3]]; 
		[obje addLastPoint:valu]; 
	}
}



- (void) showMap{
	[windMapp makeKeyAndOrderFront:nil];
}



- (void) verifyZoomSetLocations {

	// Acciones automaticas cuando camvia el Zoom
}



- (void) updatePopup {
	[mobiPopu removeAllItems];
	var aliaArra = [hashObjs allKeys];
	for ( var i = 0; i < [aliaArra count]; i++ ) {
		var aliaTitl = [aliaArra objectAtIndex:i];
		[mobiPopu addItemWithTitle:aliaTitl];
	}
}


- (void) windowMapSetupEnd {

	count++;

    myMap = [myMapView gMap];

    //[drawView setMap:map];
    //[drawCtrl setMyMap:map];


	if ( (myMap == null || typeof(myMap) === 'undefined') && count<5) {
	    setTimeout(function() {[self windowMapSetupEnd];}, 100);
	    return;
    }

	google.maps.event.addDomListener(window, "resize", function() {
    	var center = myMap.getCenter();
    	google.maps.event.trigger(myMap, "resize");
    	myMap.setCenter(posi);
	});

	google.maps.event.addListenerOnce(myMap, 'idle', function() {
   		google.maps.event.trigger(myMap, 'resize');
	});
	setTimeout(function(){myMap.setCenter(posi);},1000);

   	google.maps.event.addListener(myMap, 'zoom_changed', function() {
	    imagZoom = myMap.getZoom();
	    [self verifyZoomSetLocations];
	  });

	aLblMin = [[CPTextField alloc] initWithFrame:CGRectMake(10,20, 30,20)];
	[aLblMin setFont:[CPFont fontWithName:@"Arial" size:8]];
	[aLblMin setStringValue:@""];

	//[self mapFromGoogle];
	mobiPopu = [self addPopupButtonMap:@"Enfocar dispositivo" TFPosX:4 TFPosY:4 TFWidth:200 TFHeight:24  VView:windMappContView pullsDown:YES];
	[mobiPopu setTarget:self];
	[mobiPopu setAction:@selector(action_buttons:)];

    refrButt = [self getButtonMap:CGRectMake( 215, 4 , 139,24 ) VView:windMappContView sizeToFit:NO Action:@selector(action_buttons:) Target:self Title:@"Refrescar" icon:@"Resources/img/refresh.png"];
    [self updatePopup];

    [self refreshTracking];																							
}

@end