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

#import "DevicesListViewController.h"

@interface DevicesListViewController ()

@end

@implementation DevicesListViewController
@synthesize urlConnection,mutableData,devicesTBVw;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = @"Device List";
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    devicesTBVw.backgroundColor = [UIColor clearColor];
    devicesTBVw.backgroundView = nil;
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7)
    {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    
    
    activity = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    [activity setHidesWhenStopped:YES];
    [activity setFrame:CGRectMake(0, 0, 40, 40)];
    
    actvtyBBtn = [[UIBarButtonItem alloc]initWithCustomView:activity];
    UIBarButtonItem *flex = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    
    [self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:flex,actvtyBBtn,flex,nil]];
    
    
    [activity startAnimating];
    //  http://mocal.mobi/listDevices.php?username=whiletrue@hotmail.com&password=123
    if(self.mutableData !=nil)
    {
        self.mutableData = nil;
    }
    self.mutableData = [NSMutableData data];
    
    //NSString *deviceId = [[UIDevice currentDevice]uniqueIdentifier];
    
    NSString *loginUrl = [NSString stringWithFormat:@"http://mialerts.info/listDevices.php?username=%@&password=%@&token=%@",  UIAPPDELEGATE.loggedUserName,  UIAPPDELEGATE.loggedPassword, UIAPPDELEGATE.dToken];
    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:@"list"];
    self.urlConnection = [[NSURLConnection alloc]initWithRequest:urlRequest delegate:self];
    
}

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

-(void)viewDidAppear:(BOOL)animated
{
    
}

#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");
    [activity stopAnimating];
    UIAlertView *connAlert = [[UIAlertView alloc]initWithTitle:@"Error" message:[error description] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [connAlert show];
    [connAlert release];

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

-(void)parseLoginResponse:(NSString *)response
{
    //NSLog(@"the response is %@",response);
    if([response rangeOfString:@"success"].location != NSNotFound)
    {
        XMLParser* xml = [[XMLParser alloc] init];
        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:@"No account available with given details" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [connAlert show];
        [connAlert release];
        [activity stopAnimating];

    }
}

-(void)parseDataWithDict:(NSMutableDictionary *)responseDict
{
    devicesArr = [[NSMutableArray alloc]init];
    NSMutableArray *parsedvalues = [responseDict objectForKey:@"Values"];
    int resCount = [parsedvalues count];
    
    for (int k =0; k<resCount; k++) {
        
        Device *idev = [Device new];
        NSDictionary *d = [parsedvalues objectAtIndex:k];
        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!=nil)
            if([idev.age length]>0)
                idev.age_sec = [idev.age intValue];
        
        if( idev.age_sec<0 || idev.age_sec>1000000)
            idev.lastSeen = [NSString stringWithFormat:@"Never seen, \tid: %@", idev.macAddress];
        else
        {
            if(idev.age_sec>3600*24)
                idev.lastSeen = [NSString stringWithFormat:@"Seen %d days ago, \tid: %@", (int)(idev.age_sec/3600/24), idev.macAddress];
            else  if(idev.age_sec<30)
                idev.lastSeen = [NSString stringWithFormat:@"Active, \tid: %@", idev.macAddress];
            else
                idev.lastSeen = [NSString stringWithFormat:@"Seen %ld s, \tid: %@", idev.age_sec, idev.macAddress];
        }
        idev.gps_age_sec=-1;
        idev.gps_age = [d valueForKey:@"gps_age"];
        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 %d s", idev.gps_age_sec];
        
        [devicesArr addObject:idev];
    }
    
    [self.devicesTBVw setDelegate:self];
    [self.devicesTBVw setDataSource:self];
    [self.devicesTBVw reloadData];
    [activity stopAnimating];

}


#pragma mark -
#pragma mark Table View datasource methods

// Required Methods

// Return the number of rows in a section
-(NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
	return [devicesArr count];
}

// Returns cell to render for each row
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *CellIdentifier = @"CellIdentifier";
	
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
	}
	
	// Configure cell
	
	NSUInteger row = [indexPath row];
	
	// Sets the text for the cell
    Device *d = [devicesArr objectAtIndex:row];

	cell.textLabel.text = 	d.title;
    /*if( d.age_sec<0 || d.age_sec>1000000)
        cell.detailTextLabel.text = [NSString stringWithFormat:@"Never seen, \tid: %@", d.macAddress];
    else
        */
    cell.detailTextLabel.text = d.lastSeen;
    // Sets the accessory for the cell
	cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	
    
	return cell;
}

// Optional

// Returns the number of section in a table view
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
	return 1;
}

#pragma mark -
#pragma mark Table View delegate methods

// Return the height for each cell
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return 50;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Device *selectedD = [devicesArr objectAtIndex:indexPath.row];
    iMapViewController *iMap = [[iMapViewController alloc]initWithNibName:@"iMapViewController" bundle:nil];
    iMap.selectedDevice = selectedD;
    [self.navigationController pushViewController:iMap animated:YES];
    
}

- (void)dealloc {
    [devicesTBVw release];
    [super dealloc];
}
@end
