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

#import "AlertsViewController.h"

@interface AlertsViewController ()

@end

@implementation AlertsViewController
@synthesize urlConnection,mutableData,alertsTBVw,tableData;
- (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.
    [self createRefreshBarButton];
    self.title =@"Alerts";
    
   /* if (UIAPPDELEGATE.isAutoUpdate == TRUE) {
        
        if (self.autoUpdateTimer==nil) {
            self.autoUpdateTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(updateAlertList) userInfo:nil repeats:YES];
        }
        
    }*/
}

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


-(void)startAutoUpdateTimer
{
    if (UIAPPDELEGATE.isAutoUpdate == TRUE) {
        
        if (self.autoUpdateTimer==nil) {
            self.autoUpdateTimer = [NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(updateAlertList) userInfo:nil repeats:YES];
        }
        
    }

    if (refreshBBtn.isEnabled == NO) {
        refreshBBtn.enabled = YES;
        
    }
}

-(void)viewWillAppear:(BOOL)animated
{
      [self callWSForAlerts];
}
-(void)viewDidDisappear:(BOOL)animated
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(startAutoUpdateTimer) object:NULL];
    if ([self.autoUpdateTimer isValid]) {
        [self.autoUpdateTimer invalidate];
        self.autoUpdateTimer = nil;
      }
    if (refreshBBtn.isEnabled == NO) {
        refreshBBtn.enabled = YES;

    }
    
    UIAPPDELEGATE.isAlertsFirstUpdate =FALSE;

}
-(void)updateAlertList
{
    if ([self.autoUpdateTimer isValid]) {
        [self.autoUpdateTimer invalidate];
        self.autoUpdateTimer = nil;
    }

    [self callWSForAlerts];
}
#pragma mark iDing WSCalls

-(void)callWSForAlerts
{
    [activity startAnimating];
    if(self.mutableData!=nil)
    {
        self.mutableData=nil;
    }
    self.mutableData = [NSMutableData data];
    //http://mocal.mobi/listAlerts.php?username=whiletrue@hotmail.com&password=123
    //NSString *deviceId = [[UIDevice currentDevice]uniqueIdentifier];
    
    NSString *loginUrl = [NSString stringWithFormat:@"http://www.theautoi.com/listAlerts.php?username=%@&password=%@&token=%@",  UIAPPDELEGATE.loggedUserName,  UIAPPDELEGATE.loggedPassword, UIAPPDELEGATE.dToken];
    NSLog(@"list Alerts: %@", 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:@"GetAlerts"];
    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");
    UIAlertView *connAlert = [[UIAlertView alloc]initWithTitle:@"Error" message:[error description] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [connAlert show];
    [connAlert release];
    [activity stopAnimating];

}
-(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:@"alert"];
        [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];
        [activity stopAnimating];
    } 
}

-(void)parseDataWithDict:(NSMutableDictionary *)responseDict
{
    NSMutableArray *parsedvalues = [responseDict objectForKey:@"Values"];
    int g = [parsedvalues count];
    NSMutableArray *finalParsedArr = [[NSMutableArray alloc]init];
    for (int k =0; k<g; k++) {
        Alert *ialert    = [Alert new];

        NSDictionary *d = [parsedvalues objectAtIndex:k];
        ialert.age              = [d valueForKey:@"age"];
        ialert.alertTypesId     = [d valueForKey:@"alert_types_id"];
        ialert.alertTypesTitle  = [d valueForKey:@"alert_types_title"];
        ialert.deviceSerial     = [d valueForKey:@"device_serial"];
        ialert.deviceTitle      = [d valueForKey:@"device_title"];
        ialert.deviceId         = [d valueForKey:@"id"];
        ialert.latt             = [d valueForKey:@"lat"];
        ialert.longg            = [d valueForKey:@"lng"];
        ialert.deviceType       = [d valueForKey:@"type"];
        ialert.updateTimeStamp  = [d valueForKey:@"update_timestamp"];
        ialert.impactLevel      = [d valueForKey:@"level"];
        [finalParsedArr addObject:ialert];
    }
    // uodate
    
    self.tableData =[[NSMutableArray alloc]initWithArray:finalParsedArr];
    [alertsTBVw setDelegate:self];
    [alertsTBVw setDataSource:self];
    [alertsTBVw reloadData];
    
    if (UIAPPDELEGATE.isAlertsFirstUpdate == FALSE) {
        UIAPPDELEGATE.isAlertsFirstUpdate = TRUE;
        [[SHKActivityIndicator currentIndicator] displayCompleted:@"Updated"];
    }
    [activity stopAnimating];
    
    
    if ([self.autoUpdateTimer isValid]) {
        [self.autoUpdateTimer invalidate];
        self.autoUpdateTimer = nil;
    }
   
    [self performSelector:@selector(startAutoUpdateTimer) withObject:NULL afterDelay:0];


}

-(void)createRefreshBarButton
{
    refreshBBtn = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(callWSForAlerts)];
   
    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,refreshBBtn,flex,actvtyBBtn,flex,nil]];
    [refreshBBtn release];
    [actvtyBBtn release];
    
}
#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 [tableData 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:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        
        UILabel *idLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, 25, 30, 30)];
        [idLabel setTag:4000];
        [idLabel setBackgroundColor:[UIColor darkGrayColor]];
        [idLabel setTextColor:[UIColor whiteColor]];
        [idLabel setTextAlignment:UITextAlignmentCenter];
        [idLabel setFont:[UIFont boldSystemFontOfSize:15]];
        [cell.contentView addSubview:idLabel];
        
        UILabel *iTitle = [[UILabel alloc]initWithFrame:CGRectMake(idLabel.frame.size.width+idLabel.frame.origin.x+10, 0+5, 250, 30)];
        [iTitle setTag:4001];
        [iTitle setBackgroundColor:[UIColor clearColor]];
        [iTitle setTextColor:[UIColor blackColor]];
        [iTitle setFont:[UIFont boldSystemFontOfSize:17]];
        [iTitle setHighlightedTextColor:[UIColor whiteColor]];
        [cell.contentView addSubview:iTitle];
        
        UILabel *iTimeStamp = [[UILabel alloc]initWithFrame:CGRectMake(idLabel.frame.size.width+idLabel.frame.origin.x+10, iTitle.frame.size.height+idLabel.frame.origin.x-10, 250, 30)];
        [iTimeStamp setTag:4002];
        [iTimeStamp setBackgroundColor:[UIColor clearColor]];
        [iTimeStamp setTextColor:[UIColor lightGrayColor]];
        [cell.contentView addSubview:iTimeStamp];
        
        UILabel *impactLevelLbl = [[UILabel alloc]initWithFrame:CGRectMake(idLabel.frame.size.width+idLabel.frame.origin.x+10, iTimeStamp.frame.size.height+idLabel.frame.origin.x+10, 250, 30)];
        [impactLevelLbl setTag:4003];
        [impactLevelLbl setBackgroundColor:[UIColor clearColor]];
        [impactLevelLbl setTextColor:[UIColor lightGrayColor]];
        [cell.contentView addSubview:impactLevelLbl];
        
        [idLabel     release];
        [iTitle      release];
        [iTimeStamp  release];
        [impactLevelLbl release];

	}
	
	// Configure cell
    NSUInteger row = [indexPath row];
	//alert_types_id,device_title,update_timestamp
	// Sets the text for the cell
    Alert *d = [tableData objectAtIndex:row];
    UILabel *leftIdLBL          = (UILabel *)[cell viewWithTag:4000];
    UILabel *topTitleLBL        = (UILabel *)[cell viewWithTag:4001];
    UILabel *btmTimeStampLBL    = (UILabel *)[cell viewWithTag:4002];
    UILabel *impactLBL    = (UILabel *)[cell viewWithTag:4003];
    
    leftIdLBL.text       =  d.alertTypesId;
	topTitleLBL.text     = 	d.deviceTitle;
    btmTimeStampLBL.text =  d.updateTimeStamp;
    impactLBL.text       =  [NSString stringWithFormat:@"Impact Level : %@",d.impactLevel];
    
    
	cell.accessoryType   = UITableViewCellAccessoryDisclosureIndicator;
    
    [cell setBackgroundColor:[UIColor blackColor]];
    [[cell textLabel] setTextColor:[UIColor greenColor]];
    [[cell textLabel] setBackgroundColor:[UIColor blackColor]];
    
    
    [[cell detailTextLabel] setBackgroundColor:[UIColor blackColor]];
    [[cell detailTextLabel] setTextColor:[UIColor greenColor]];
    
    [leftIdLBL setBackgroundColor:[UIColor blackColor]];
    [leftIdLBL setTextColor:[UIColor greenColor]];
    
    [impactLBL setBackgroundColor:[UIColor blackColor]];
    [impactLBL setTextColor:[UIColor greenColor]];

    [topTitleLBL setBackgroundColor:[UIColor blackColor]];
    [topTitleLBL setTextColor:[UIColor greenColor]];
    [btmTimeStampLBL  setBackgroundColor:[UIColor blackColor]];
    [btmTimeStampLBL setTextColor:[UIColor greenColor]];
    
	return cell;
}

// 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 80;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Alert *selectedAlrt = [tableData objectAtIndex:indexPath.row];
    AlertDetailsViewController *iAlrtD = [[AlertDetailsViewController alloc]initWithNibName:@"AlertDetailsViewController" bundle:nil];
    iAlrtD.choosedAlert = selectedAlrt;
    [self.navigationController pushViewController:iAlrtD animated:YES];
}


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