//
//  iMapViewController.m
//  iDing
//
//  Created by Macbook Pro on 29/01/13.
//  Copyright (c) 2013 Abusamy Ltd.. All rights reserved.
//

#import "iMapViewController.h"
#import "RegexKitLite.h"

@interface iMapViewController ()

@end

@implementation iMapViewController
@synthesize devicesMapview,refreshBBtn,selectedDevice,addAnnotation,userLocationAnnotation;
@synthesize urlConnection,mutableData,autoUpdateTimer;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    //http://mocal.mobi/locateDevice.php?username=whiletrue@hotmail.com&password=123&trackeddeviceid=7

    [self createRefreshBarButton];
    [self       refreshDevicesMap]; // first refresh map with initial device values
    [self callWSForDeviceLocation]; // then call WS for device location parameters
    [self.devicesMapview setDelegate:self];
    [self.devicesMapview setShowsUserLocation:YES];
    
    self.title = self.selectedDevice.title;
    
        
}

-(void)viewDidDisappear:(BOOL)animated
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(startAutoUpdateTimer) object:NULL];

    if ([self.autoUpdateTimer isValid]) {
        [self.autoUpdateTimer invalidate];
        self.autoUpdateTimer = nil;
    }
}
-(void)startAutoUpdateTimer
{
    if (UIAPPDELEGATE.isAutoUpdate == TRUE) {
        
        if (self.autoUpdateTimer==nil) {
            self.autoUpdateTimer = [NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(updateMap) userInfo:nil repeats:YES];
        }
        
    }
    
    if (refreshBBtn.isEnabled == NO) {
        refreshBBtn.enabled = YES;
        
    }
}

- (NSMutableArray *)decodePolyLine: (NSMutableString *)encoded
{
    [encoded replaceOccurrencesOfString:@"\\\\" withString:@"\\" options:NSLiteralSearch range:NSMakeRange(0, [encoded length])];
    NSInteger len = [encoded length];
    NSInteger index = 0;
    NSMutableArray *array = [[NSMutableArray alloc] init];
    NSInteger lat=0;
    NSInteger lng=0;
    while (index < len)
    {
        NSInteger b;
        NSInteger shift = 0;
        NSInteger result = 0;
        do
        {
            b = [encoded characterAtIndex:index++] - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        NSInteger dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
        lat += dlat;
        shift = 0;
        result = 0;
        do
        {
            b = [encoded characterAtIndex:index++] - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        NSInteger dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
        lng += dlng;
        NSNumber *latitude = [[NSNumber alloc] initWithFloat:lat * 1e-5];
        NSNumber *longitude = [[NSNumber alloc] initWithFloat:lng * 1e-5];
        //printf("[%f,", [latitude doubleValue]);
        //printf("%f]", [longitude doubleValue]);
        CLLocation *loc = [[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]];
        [array addObject:loc];
    }
    return array;
}

-(NSArray*) calculateRoutesFrom:(CLLocationCoordinate2D) f to: (CLLocationCoordinate2D) t
{
    NSString* saddr = [NSString stringWithFormat:@"%f,%f", f.latitude, f.longitude];
    NSString* daddr = [NSString stringWithFormat:@"%f,%f", t.latitude, t.longitude];
    
    NSString* apiUrlStr = [NSString stringWithFormat:@"http://maps.google.com/maps?output=dragdir&saddr=%@&daddr=%@", saddr, daddr];
    NSURL* apiUrl = [NSURL URLWithString:apiUrlStr];
    //NSLog(@"api url: %@", apiUrl);
    NSError* error = nil;
    NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl encoding:NSASCIIStringEncoding error:&error];
    NSString *encodedPoints = [apiResponse stringByMatching:@"points:\\\"([^\\\"]*)\\\"" capture:1L];
    
    return [self decodePolyLine:[encodedPoints mutableCopy]];
}

-(void)viewDidAppear:(BOOL)animated
{
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)callWSForDeviceLocation
{
    if(self.mutableData !=nil)
    {
        self.mutableData = nil;
    }
    self.mutableData = [NSMutableData data];
    
    //NSString *deviceId = [[UIDevice currentDevice]uniqueIdentifier];
    
    NSString *loginUrl = [NSString stringWithFormat:@"http://mialerts.info/locateDevice.php?username=%@&password=%@&token=%@&trackeddeviceid=%@",  UIAPPDELEGATE.loggedUserName,  UIAPPDELEGATE.loggedPassword, UIAPPDELEGATE.dToken,self.selectedDevice.deviceId];
    NSLog(@"Device Location WS: %@", loginUrl);
    
    NSURL *url = [NSURL URLWithString:loginUrl];
    NSMutableURLRequest *urlRequest = [[[NSMutableURLRequest alloc]initWithURL:url]autorelease];
    if(self.urlConnection != nil)
    {
        [self.urlConnection release];
        self.urlConnection = nil;
    }
    [self.urlConnection setAccessibilityHint:@"TrackDevice"];
    self.urlConnection = [[NSURLConnection alloc]initWithRequest:urlRequest delegate:self];
    

}
#pragma mark NSURLConnection Delegates
#pragma mark Connection callbacks

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    //
	[self.mutableData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	[self.mutableData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"error");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    
    NSString *response = [[NSString alloc]initWithData:self.mutableData encoding:NSASCIIStringEncoding];
     //NSLog(@"the response is %@",response);
   
         [self parseLoginResponse:response];
}

-(void)parseLoginResponse:(NSString *)response
{
    
    //NSLog(@"the response is %@",response);
    if([response rangeOfString:@"success"].location != NSNotFound)
    {
        XMLParser* xml = [[XMLParser alloc] init];
        NSMutableDictionary* parsedDict = [xml parseXML:response mainElement:@"device"];
        // NSLog(@"parsed Dict %@",parsedDict);
        [self parseDataWithDict:parsedDict];

    }
    else if([response rangeOfString:@"error"].location != NSNotFound)
    {
         UIAlertView *connAlert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"something went wrong" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
         [connAlert show];
         [connAlert release];
        
    }
    
   }
-(void)parseDataWithDict:(NSMutableDictionary *)responseDict
{
    NSMutableArray *parsedvalues = [responseDict objectForKey:@"Values"];
    // uodate 
        Device *idev    = self.selectedDevice;
        NSDictionary *d = [parsedvalues objectAtIndex:0];
        idev.age        = [d valueForKey:@"age"];
        idev.deviceId   = [d valueForKey:@"id"];
        idev.latt       = [d valueForKey:@"lat"];
        idev.longg      = [d valueForKey:@"lng"];
        idev.macAddress = [d valueForKey:@"mac"];
        idev.serialNo   = [d valueForKey:@"serial"];
        idev.title      = [d valueForKey:@"title"];
        idev.updateDate = [d valueForKey:@"update_timestamp"];
    idev.age_sec = -1;
    idev.gps_age = nil;
    
    if(idev.age!=NULL)
        if([idev.age length]>0)
            idev.age_sec = [idev.age intValue];
    
    if( idev.age_sec<0 || idev.age_sec>1000000)
        idev.lastSeen = @"Never seen";
    else
        idev.lastSeen = [NSString stringWithFormat:@"Seen %ld s", idev.age_sec];
    
    idev.gps_age = [d valueForKey:@"gps_age"];
    idev.gps_age_sec=-1;
    if(idev.gps_age!=nil)
        if([idev.gps_age length]>0)
            idev.gps_age_sec = [idev.gps_age intValue];
    
    if( idev.gps_age_sec<0 || idev.gps_age_sec>1000000)
        idev.lastFix = @"No recent fix";
    else
        idev.lastFix = [NSString stringWithFormat:@"GPS Fix %ld s", idev.gps_age_sec];
    
    [self refreshDevicesMap];
    
    
    if ([self.autoUpdateTimer isValid]) {
        [self.autoUpdateTimer invalidate];
        self.autoUpdateTimer = nil;
    }
    
    [self performSelector:@selector(startAutoUpdateTimer) withObject:NULL afterDelay:0];
    
    

    
}

-(CLLocationCoordinate2D) addressLocation {
  
    double latitude = [self.selectedDevice.latt doubleValue];
    double longitude = [self.selectedDevice.longg doubleValue];
    CLLocationCoordinate2D location;
    location.latitude = latitude;
    location.longitude = longitude;
    return location;
}

- (MKAnnotationView *) mapView:(MKMapView *)mapVw viewForAnnotation:(id <MKAnnotation>) annotation{
    
    if ([annotation isKindOfClass:[MKUserLocation class]])
        return nil;
    if ([annotation isKindOfClass:[NVPolylineAnnotation class]]) {
		return [[[NVPolylineAnnotationView alloc] initWithAnnotation:annotation mapView:self.devicesMapview] autorelease];
	}

    annView = (MKPinAnnotationView*)[mapVw dequeueReusableAnnotationViewWithIdentifier:@"currentloc"];
    if (annView == nil) {
        annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentloc"];
        
       // UIImage *mapImage       = [UIImage imageNamed:@"downMark.png"];
       // annView.image           = mapImage;
                   annView.pinColor = MKPinAnnotationColorGreen;
        annView.canShowCallout  = YES;
        [annView setSelected:YES animated:YES];
        annView.calloutOffset = CGPointMake(-5, 5);
    }
    else
    {

        annView.annotation = annotation;
        [annView setSelected:YES animated:YES];
    }
    return annView;
    [annView release];
}


-(void)createRefreshBarButton
{
    refreshBBtn = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(callWSForDeviceLocation)];
    
    routeBBtn = [[UIBarButtonItem alloc]initWithTitle:@"R" style:UIBarButtonItemStyleBordered target:self action:@selector(drawDeviceroutemMap)];
    UIBarButtonItem *flex = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
   /* UIToolbar *iMapToolbar = [[UIToolbar alloc]init];
    [iMapToolbar setFrame:CGRectMake(0, 0, 100, 40)];
    [iMapToolbar setItems:[NSArray arrayWithObjects:flex,routeBBtn,flex,refreshBBtn,nil]];
    [iMapToolbar setBackgroundColor:[UIColor clearColor]];*/
    
    [self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:flex,refreshBBtn,flex,routeBBtn,flex,nil]];
    [refreshBBtn release];
    [routeBBtn release];

    
}

-(void)drawDeviceroutemMap
{
    // 23.985853 31.978242
    CLLocationDegrees lat = [self.selectedDevice.latt doubleValue];
    CLLocationDegrees lon = [self.selectedDevice.longg doubleValue];
    CLLocationCoordinate2D coordinate  = CLLocationCoordinate2DMake(lat,lon);
    
   // CLLocationDegrees dlat = self.devicesMapview.userLocation.coordinate.latitude;
   // CLLocationDegrees dlon = self.devicesMapview.userLocation.coordinate.longitude;
    CLLocationDegrees dlat = 30.04532159026885;
    CLLocationDegrees dlon = 31.048736572265625;
    CLLocationCoordinate2D ddcoordinate  = CLLocationCoordinate2DMake(dlat,dlon);
    
    NSArray *points = [self calculateRoutesFrom:coordinate to:ddcoordinate];
   // NSLog(@"points %@",points);
    
    if (polyLineannotation==nil) {
        polyLineannotation = [[[NVPolylineAnnotation alloc] initWithPoints:points mapView:self.devicesMapview] autorelease];
        [self.devicesMapview addAnnotation:polyLineannotation];
    }
}
-(void)refreshDevicesMap
{
    // ------------------- Load Device on Current MapView
    MKCoordinateRegion region;
    MKCoordinateSpan span;
    span.latitudeDelta=0.2;
    span.longitudeDelta=0.2;
    
    CLLocationCoordinate2D location = [self addressLocation];
    region.span=span;
    region.center=location;
    if(addAnnotation != nil) {
        [self.devicesMapview removeAnnotation:addAnnotation];
        addAnnotation = nil;
    }
    
    addAnnotation = [[iDeviceAdressAnnotation alloc] initWithCoordinate:location];
    addAnnotation.mTitle    = self.selectedDevice.title;
    addAnnotation.mSubTitle = self.selectedDevice.serialNo;
    addAnnotation.mlastSeen = self.selectedDevice.lastSeen;
    addAnnotation.mlastFix = self.selectedDevice.lastFix;
    
    [self.devicesMapview addAnnotation:addAnnotation];
    [self.devicesMapview selectAnnotation:addAnnotation animated:FALSE];
    [[self.devicesMapview viewForAnnotation:addAnnotation] setSelected:YES animated:NO];
    [self.devicesMapview setRegion:region animated:TRUE];
    [self.devicesMapview regionThatFits:region];
    // -----------------------------------------------------

    refreshBBtn.enabled = YES;
    routeBBtn.enabled = YES;
}


-(void)updateMap
{
    refreshBBtn.enabled = NO;
    routeBBtn.enabled = NO;
    [self callWSForDeviceLocation];
}
@end
