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

#import "SettingsViewController.h"
#import "XMLParser.h"

@interface SettingsViewController ()

@end

@implementation SettingsViewController
@synthesize settingsTBVw,mutableData,urlConnection;

;
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent: (NSInteger)component
{
    if(devicesArr==NULL)
        return 0;
    return [devicesArr count];
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row   forComponent:(NSInteger)component
{
    if(devicesArr==NULL)
        return @"Besmella";
    if([devicesArr count]<=row)
        return @"Besmella";
    Device *idev = [devicesArr objectAtIndex:row];
    return idev.title;//.serialNo;;//@"Besmella";
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row   inComponent:(NSInteger)component
{
    NSLog(@"Thanks.. selected %ld and %ld", (long) row, (long) component);
    devices_picker.hidden = YES;
    
    Device *idev = [devicesArr objectAtIndex:row];
    NSString* BBBKID = idev.serialNo;
    // [self openStreamingVideoPageAfterAWhile:BBBKID];
    [UIAPPDELEGATE setBBBKID:BBBKID];
    [settingsTBVw reloadData];
    //[self performSelector:@selector(openStreamingPage:) withObject:BBBKID afterDelay:0.1];
}

- (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.
    settingsTBVw .backgroundColor = [UIColor clearColor];
    settingsTBVw.backgroundView = nil;
    [settingsTBVw setDelegate:self];
    [settingsTBVw setDataSource:self];
    [settingsTBVw reloadData];
    self.title = @"Settings";
    //self.automaticallyAdjustsScrollViewInsets = NO;
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
// Return the number of rows in a section
-(NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
	return 4;
}

// Returns cell to render for each row
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *CellIdentifier = @"CellIdentifier";
	
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	// Autoupdate,pushnotifications,relogin
    
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        CGRect cellFrame =  cell.frame;
        UISwitch *stngToggle =[[UISwitch alloc]initWithFrame:CGRectMake(cellFrame.size.width-99, 11.5f,79, 27)];
        [stngToggle setTag:2001];
        [cell.contentView addSubview:stngToggle];
               
        
	}
	[cell.textLabel setBackgroundColor:[UIColor clearColor]];
	// Configure cell
	//alert_types_id,device_title,update_timestamp
	// Sets the text for the cell
    UISwitch *stngToggle =(UISwitch*)[cell viewWithTag:2001];
      cell.selectionStyle = UITableViewCellSelectionStyleNone;
    switch (indexPath.row) {
        case 0:
        {
            cell.textLabel.text = @"Auto Update";
            [stngToggle addTarget:self action:@selector(autoUpdateToggled:) forControlEvents:UIControlEventValueChanged];
          //  NSLog(@"UIAPPDELEGATE.isAutoUpdate %d",UIAPPDELEGATE.isAutoUpdate);
            if (UIAPPDELEGATE.isAutoUpdate == TRUE) {
                [stngToggle setOn:YES];
            }
        }
            break;
        case 1:
        {
            cell.textLabel.text = @"Push Notifications";
            [stngToggle addTarget:self action:@selector(pNotificationsToggled:) forControlEvents:UIControlEventValueChanged];
            if (UIAPPDELEGATE.isPushNotif == TRUE) {
                [stngToggle setOn:YES];
            }
            
            
        }
            break;
        case 3:
        {
            cell.textLabel.text = @"Auto login";
            [stngToggle addTarget:self action:@selector(pAutoLoginToggled:) forControlEvents:UIControlEventValueChanged];
            if (UIAPPDELEGATE.isAutoLogin == TRUE) {
                [stngToggle setOn:YES];
            }
            
            
        }
            break;
      /*  case 2:
        {
            cell.textLabel.text = @"Relogin";
            cell.selectionStyle = UITableViewCellSelectionStyleBlue;
            [stngToggle removeFromSuperview];

        }
            break;*/
            
        case 2:
             {
             cell.textLabel.text = [NSString stringWithFormat:@"Default Device: %@", [UIAPPDELEGATE getDefautDeviceID ]];
             cell.selectionStyle = UITableViewCellSelectionStyleBlue;
             [stngToggle removeFromSuperview];
             }
             break;
        default:
            break;
    }
    
    
     
	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 50;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 2) {
       // [self moveToLoginPage];
    
        [self selectDevice: 4];
    }
}

-(void) selectDevice: (int)cams
{
    BOOL isInternetAvailable = [UIAPPDELEGATE isInternetAvailable];
    
    if(isInternetAvailable == FALSE)
    {// TODO: change this to hud
        /* UIAlertView *connAlert = [[UIAlertView alloc]initWithTitle:@"Connection Alert" message:@"Please check internet connection" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
         [connAlert show];
         [connAlert release];
         
         */
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"Please check internet connection!";
        hud.margin = 10.f;
        hud.yOffset = 150.f;
        hud.removeFromSuperViewOnHide = YES;
        
        [hud hide:YES afterDelay:3];
        
        return;
    }
    if(HUD!=NULL)
    {// change this to hud
        
        HUD.labelText = @"Please wait!";
        return;
    }
    
    [ self showProgress: @"Connecting"];
    
    //    NSString *deviceId = [[UIDevice currentDevice]uniqueIdentifier];
    //http://mialerts.info/request_manual_video.php?username=whiletrue@hotmail.com&password=12
    NSString *deviceId = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    
    NSString *loginUrl = [NSString stringWithFormat:@"http://mialerts.info/listDevices.php?username=%@&password=%@&token=%@&deviceid=%@&cams=%d", UIAPPDELEGATE.loggedUserName, UIAPPDELEGATE.loggedPassword,UIAPPDELEGATE.dToken,deviceId,cams];
    
    NSURL *url = [NSURL URLWithString:loginUrl];
    NSMutableURLRequest *urlRequest = [[[NSMutableURLRequest alloc]initWithURL:url]autorelease];
    NSLog(@"RequestSreamingVideo Url=%@" , loginUrl);
    
    if(self.urlConnection != nil)
    {
        [self.urlConnection release];
        self.urlConnection = nil;
    }
    if(self.mutableData !=nil)
    {
        self.mutableData = nil;
    }
    self.mutableData = [NSMutableData data];
    
    self.urlConnection = [[NSURLConnection alloc]initWithRequest:urlRequest delegate:self];
    [self.urlConnection setAccessibilityHint:@"Devices List"];
};

-(void) showProgress: (NSString*) job
{
    if(HUD!=nil)
        [self endProgress];
    HUD = [[MBProgressHUD alloc]initWithView:self.view];
    HUD.delegate = self;
    HUD.mode = MBProgressHUDModeText;
    HUD.labelText = job;// @"Loading...";
    [self.navigationController.view.superview addSubview:HUD];
    
    [HUD show:YES];
    
}

-(void) endProgress
{
    if(HUD!=nil)
    {
        [HUD hide:YES afterDelay:0.3];
        [HUD removeFromSuperview];
        HUD = nil;
    }
}

-(void) endProgressWithMessage: (NSString*) msg
{
    if(HUD!=nil)
    {
        HUD.labelText = msg;
        HUD.removeFromSuperViewOnHide = YES;
        [HUD hide:YES afterDelay:3];
        HUD = nil;
    }
}

-(void)moveToLoginPage
{
    UIAPPDELEGATE.loggedPassword = @"";
    
    [UIAPPDELEGATE saveSettings];
    [self.navigationController popToViewController:[[self.navigationController viewControllers]objectAtIndex:0] animated:YES];
}

-(void)autoUpdateToggled:(UISwitch *)sender
{
   // NSLog(@"Auto update toggled");
    if (sender.on) {
        UIAPPDELEGATE.isAutoUpdate = TRUE;
    }else{
        UIAPPDELEGATE.isAutoUpdate = FALSE;
    }
    [UIAPPDELEGATE saveSettings];
}


-(void)pAutoLoginToggled:(UISwitch *)sender
{
    //  NSLog(@"pNotificationsToggled");
    if (sender.on) {
        UIAPPDELEGATE.isAutoLogin = TRUE;
    }else{
        UIAPPDELEGATE.isAutoLogin = FALSE;
    }
    [UIAPPDELEGATE saveSettings];
}

-(void)pNotificationsToggled:(UISwitch *)sender
{
    //  NSLog(@"pNotificationsToggled");
    if (sender.on) {
        UIAPPDELEGATE.isPushNotif = TRUE;
    }else{
        UIAPPDELEGATE.isPushNotif = FALSE;
    }
    [UIAPPDELEGATE saveSettings];
}

- (void)dealloc {
    NSLog(@"dealloc8");

    [settingsTBVw release];
    [devices_picker release];
    [super dealloc];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    //
   /* if(connection!=nil && [[connection accessibilityHint] isEqualToString:@"GetVideos"] )
    {
        [self.mutableDataVideos setLength:0];
    }
    else */ if(connection!=nil && [[connection accessibilityHint] isEqualToString:@"Devices List"] )
    {
        [self.mutableData setLength:0];
    }
    else
        [self.mutableData setLength:0];
}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    /*if(connection!=nil && [[connection accessibilityHint] isEqualToString:@"GetVideos"] )
    {
        [self.mutableDataVideos appendData:data];
    }
    else */ if(connection!=nil && [[connection accessibilityHint] isEqualToString:@"Devices List"] )
    {
        [self.mutableData appendData:data];
    }
    else
        [self.mutableData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"error3");
    [self endProgressWithMessage:@"Request Error"];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *response = nil;//[[NSString alloc]initWithData:self.mutableData encoding:NSASCIIStringEncoding];
    if(connection!=nil && [[connection accessibilityHint] isEqualToString:@"GetVideos"] )
    {
        //response = [[NSString alloc]initWithData:self.mutableDataVideos encoding:NSASCIIStringEncoding];
    }
    else
        response = [[[NSString alloc]initWithData:self.mutableData encoding:NSASCIIStringEncoding] autorelease];
    
    // NSLog(@"the response is %@",response);
    //if([connection.accessibilityHint isEqualToString:@"Login"])
    if(connection!=nil)
    {/*
        if([[connection accessibilityHint] isEqualToString:@"GetVideos"] )
        {
            [self parseVideosResponse:response :connection];
            if(UIAPPDELEGATE.isAutoUpdate)
                [self callWSAfterAWhile];
        }
        else if([[connection accessibilityHint] isEqualToString:@"User Video"] )
            [self parseUserVideoResponse:response];
        else */
        if(connection!=nil && [[connection accessibilityHint] isEqualToString:@"Devices List"] )
        {
            [self parseDevicesResponse:response];
        }
        else
            NSLog(@"unknown response received: %@", [connection accessibilityHint] );
    }
}


-(void) parseDevicesResponse:(NSString *)response
{
    NSLog(@"the Devices response is %@",response);
    if([response rangeOfString:@"success"].location != NSNotFound)
    {
        XMLParser* xml = [[XMLParser alloc] init];
        NSMutableDictionary *parsedDict;
        
        parsedDict = [xml parseXML:response mainElement:@"device"];
        // NSLog(@"parsed Dict %@",parsedDict);
        [self parseDataWithDict:parsedDict];
        
        
        int nNumberOfDevices = [devicesArr count];
        
        // only one device is there... open the streaming page
        // parse devices
        
        //if more than one device then show a list to chose from.
        
        // if zero devices show message
        
        // if one device just show the streaming page with that device
        
        if(nNumberOfDevices==1)
        {
            [self endProgress];
            //[self endProgressWithMessage:@"Connecting..."];
            Device *idev = [devicesArr objectAtIndex:0];
            NSString* BBBKID = idev.serialNo;
            [UIAPPDELEGATE setBBBKID:BBBKID];
        } else if(nNumberOfDevices>1)
        {
            [self endProgress];
            [self performSelector:@selector(showDevicesList) withObject:nil afterDelay:.3];
            
            //   [self showDevicesListForstreaming];
        }
        else
            [self endProgressWithMessage:@"No devices information found!"];
    }
    else if([response rangeOfString:@"already"].location != NSNotFound)
    {
        [self endProgressWithMessage:@"Handling previous request"];
    }
    else if([response rangeOfString:@"error"].location != NSNotFound)
    {
        [self endProgressWithMessage:@"Error requesting a stream!"];
        return;
    }
    else
        [self endProgress];
}

-(void) showDevicesList
{
    [devices_picker reloadAllComponents];
    devices_picker.hidden = NO;
    
}

-(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"];
        [devicesArr addObject:idev];
    }
}

@end
