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

#import "Reachability.h"
#import "MainMenuViewController.h"

@interface MainMenuViewController ()

@end

@implementation MainMenuViewController
@synthesize mainMenuTBVw,mutableData,mutableDataVideos,urlConnection,urlConnectionBufferVideos,buffer_file_path,files_todownload,downloadTask1,devicesArr;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    
    devices_picker.hidden = true;
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    mainMenuTBVw.backgroundColor = [UIColor clearColor];
    mainMenuTBVw.backgroundView = nil;
    [self.navigationItem setHidesBackButton:YES];
    menuTableData = [[NSArray alloc]initWithObjects:@"List of Devices",@"Alerts",@"Videos",@"Settings",@"Record Video",@"Videos Mux", @"Stream over Sockets", @"Stream over HTTP",/* @"Delays",*/  @"Logout", nil];
    [self.mainMenuTBVw setDelegate:self];
    [self.mainMenuTBVw setDataSource:self];
    self.title = @"Menu";
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7)
    {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    files_todownload = [[NSMutableArray alloc]init];
    self.session = [self backgroundSession];
    [self callWSForVideos];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:YES];
    [self.mainMenuTBVw reloadData];
}

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

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

    [mainMenuTBVw release];
    [devicesPicker release];
    [devices_picker release];
    [super dealloc];
}


#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 [menuTableData 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
	cell.textLabel.text = [menuTableData objectAtIndex:row];
	
		// 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;
}


// This method is run when the user taps the row in the tableview
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    switch (indexPath.row) {
        case 0:{
            DevicesListViewController *dv = [[[DevicesListViewController alloc]initWithNibName:@"DevicesListViewController" bundle:nil]autorelease];;
            [self.navigationController pushViewController:dv animated:YES];

        }
            break;
        case 1:
        {
             AlertsViewController *dv = [[[AlertsViewController alloc]initWithNibName:@"AlertsViewController" bundle:nil]autorelease];;
            [self.navigationController pushViewController:dv animated:YES];

           
        }
             break;
        case 2:
        {
            VideosListViewController *dv = [[[VideosListViewController alloc]initWithNibName:@"VideosListViewController" bundle:nil]autorelease];;
            dv.isVideoMuxList = FALSE;
            [self.navigationController pushViewController:dv animated:YES];
        }
        break;
        case 3:
        {
            SettingsViewController *dv = [[[SettingsViewController alloc]initWithNibName:@"SettingsViewController" bundle:nil]autorelease];;
            [self.navigationController pushViewController:dv animated:YES];
        }
        break;
        case 4:
        {
            [ self requst_manual_video];
            break;
        }
        case 5:
        {
            VideosListViewController *dv = [[[VideosListViewController alloc]initWithNibName:@"VideosListViewController" bundle:nil]autorelease];;
            dv.isVideoMuxList = TRUE;
            
            [self.navigationController pushViewController:dv animated:YES];
            
            //  break;
            /*
             VideosMuxListViewController *dv = [[VideosMuxListViewController alloc]initWithNibName:@"VideosMuxListViewController" bundle:nil];
             [self.navigationController pushViewController:dv animated:YES];
             */
            
        }
            break;
        case 6:
            [ self startStreaming: 9];
            //[self openStreamingPage: UIAPPDELEGATE.BBBKID bSockets:TRUE streamingType:@"9"];

        break;
        case 7:
            [ self startStreaming: 4];
            break;
        /*case 8:
        {
            StatisticsViewController *dv = [[[StatisticsViewController alloc]initWithNibName:@"StatisticsViewController" bundle:nil]autorelease];;
            [self.navigationController pushViewController:dv animated:YES];
        }
        break;*/
        case 8:
        {
            //            logout
            UIAPPDELEGATE.loggedPassword = @"";
            [UIAPPDELEGATE saveSettings];
           // [self.navigationController popToViewController:[[self.navigationController viewControllers]objectAtIndex:0] animated:YES];
            [self.navigationController popViewControllerAnimated:YES];

        }

        default:
            break;
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

-(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) startStreaming: (int)cams
{
    BOOL isInternetAvailable = [self 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/request_streaming_video.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:[NSString stringWithFormat:@"Streaming Video %d", cams]];
};

-(void) openStreaming4VideoPageAfterAWhile: (NSString*)BBBKID
{
    [self performSelector:@selector(openStreamingPage4:) withObject:BBBKID afterDelay:3];
}

//(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
-(void) openStreamingPage: (NSString*)BBBKID bSockets:(BOOL)bSockets streamingType:(NSString*) streamingType
{
    FourStreamsViewController *dv = [[[FourStreamsViewController alloc]initWithNibName:@"FourStreamsViewController" bundle:nil]autorelease];
    dv.cams = streamingType;//@"4";
    dv.BBBKID = BBBKID;
    dv.bSockets = bSockets;
    [UIAPPDELEGATE setBBBKID:BBBKID];
    [self.navigationController pushViewController:dv animated:YES];
}

-(void) openStreamingPage4: (NSString*)BBBKID
{
    [self openStreamingPage:BBBKID bSockets:FALSE streamingType:@"4"];
}

-(BOOL)isVisible
{
    UIViewController* topMostController = self.navigationController.visibleViewController;
   // NSString* topMostControllerName = [NSString stringWithFormat:@"%s", class_getName([topMostController class])];
   // NSLog( @"Visible Controller is %@", topMostControllerName);
   // if([topMostControllerName isEqualToString:@"MainMenuViewController"])
    
     if([topMostController isKindOfClass:[MainMenuViewController class]])
        {
    //is topmost visible view controller
        return TRUE;
    }
    
    return false;
}

-(BOOL)isInternetAvailable
{
    BOOL isAvailable = FALSE;
    Reachability* reachability = [Reachability reachabilityForInternetConnection];
    NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
    if(remoteHostStatus == NotReachable)
    {
        isAvailable = FALSE;
    }
    else if (remoteHostStatus == ReachableViaWiFi)
    {
        isAvailable = TRUE;
    }
    else if (remoteHostStatus == ReachableViaWWAN)
    {
        isAvailable = TRUE;
    }
    return isAvailable;
}

-(void)requst_manual_video
{
    BOOL isInternetAvailable = [self isInternetAvailable];
    
    if(isInternetAvailable == FALSE)
    {
        UIAlertView *connAlert = [[UIAlertView alloc]initWithTitle:@"Connection Alert" message:@"Please check internet connection" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [connAlert show];
        [connAlert release];

        return;
    }

    if(self.mutableData !=nil)
    {
        self.mutableData = nil;
    }
    self.mutableData = [NSMutableData data];
    NSString *deviceId = [[[UIDevice currentDevice] identifierForVendor] UUIDString];

//    NSString *deviceId = [[UIDevice currentDevice]uniqueIdentifier];
    //http://mialerts.info/request_manual_video.php?username=whiletrue@hotmail.com&password=12
    
    NSString *loginUrl = [NSString stringWithFormat:@"http://mialerts.info/request_manual_video.php?username=%@&password=%@&token=%@&deviceid=%@", UIAPPDELEGATE.loggedUserName, UIAPPDELEGATE.loggedPassword,UIAPPDELEGATE.dToken,deviceId];
    NSURL *url = [NSURL URLWithString:loginUrl];
    NSMutableURLRequest *urlRequest = [[[NSMutableURLRequest alloc]initWithURL:url]autorelease];
    NSLog(@"RequestVideo Url=%@" , loginUrl);
    
    if(self.urlConnection != nil)
    {
        [self.urlConnection release];
        self.urlConnection = nil;
    }
    self.urlConnection = [[NSURLConnection alloc]initWithRequest:urlRequest delegate:self];
    [self.urlConnection setAccessibilityHint:@"User Video"];
    
}

- (float)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    // This will create a "invisible" footer
    return 0.01f;
}



#pragma mark NSURLConnection Delegates
#pragma mark Connection callbacks

- (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:@"Streaming Video 4"] || [[connection accessibilityHint] isEqualToString:@"Streaming Video 9"]) )
    {
        [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:@"Streaming Video 4"] || [[connection accessibilityHint] isEqualToString:@"Streaming Video 9"]) )
    {
        [self.mutableData appendData:data];
    }
    else
        [self.mutableData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"error3");
    if(UIAPPDELEGATE.isAutoUpdate)
        [self callWSAfterAWhile];
    [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]autorelease];
    }
    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:@"Streaming Video 4"] || [[connection accessibilityHint] isEqualToString:@"Streaming Video 9"]) )
        {
            [self parseStreamingVideoResponse:response connection:connection];
        }
        else
            NSLog(@"unknown response received: %@", [connection accessibilityHint] );
    }
}

-(void)parseVideosResponse:(NSString *)response :(NSURLConnection *)connection
{
    NSLog(@"the video parsing response is %@",response);
    if(response==nil && connection == nil)
    {
        // no buffered information
        //return;
        NSLog(@"No data in Buffer filename: %@", buffer_file_path);
        return;
    }
    else if([response rangeOfString:@"success"].location != NSNotFound)
    {
        XMLParser* xml = [[[XMLParser alloc] init]autorelease];

        NSMutableDictionary* parsedDict =[ [xml parseXML:response mainElement:@"video"]autorelease];
            [self parseDataWithDict:parsedDict :connection];
        
        [self saveBuffer:response ];//]:@"videos_list"];
        [self startTownloadTaskAfterAWhile];
        // NSString *str = @"hello world";
        
        // [response writeToFile:buffer_file_path atomically:TRUE encoding:NSUTF8StringEncoding error:NULL];
    }
    else if(response!=nil && [response rangeOfString:@"error"].location != NSNotFound)
    {
        NSLog(@"error in the response %@",response);

       /* UIAlertView *connAlert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Something went wrong" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [connAlert show];
        [connAlert release];*/
    }
}

-(void)callWSAfterAWhile
{
    [self performSelector:@selector(callWSForVideos) withObject:nil afterDelay:10];
}

-(void) parseStreamingVideoResponse:(NSString *)response connection:(NSURLConnection *)connection
{
    NSLog(@"the streaming video response is %@",response);
    if([response rangeOfString:@"success"].location != NSNotFound)
    {
        /* UIAlertView *connAlert = [[UIAlertView alloc]initWithTitle:@"User Video" message:@"Manual video request issued!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
         [connAlert show];
         [connAlert release];*/
        //  MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        
        // Configure for text only and offset down
        /*      hud.mode = MBProgressHUDModeText;
         hud.labelText = @"Manual video request issued!";
         hud.margin = 10.f;
         hud.yOffset = 150.f;
         hud.removeFromSuperViewOnHide = YES;
         
         [hud hide:YES afterDelay:3];
         */

            XMLParser* xml = [[XMLParser alloc] init];
            NSMutableDictionary *parsedDict;

            parsedDict = [[xml parseXML:response mainElement:@"device"]autorelease];
            // 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
        bool bSockets = FALSE;
        NSString* streamingType = @"4";
        
        if(connection!=nil &&  [[connection accessibilityHint] isEqualToString:@"Streaming Video 9"] )
        {
            bSockets = TRUE;
            streamingType = @"9";
        }
            
        
        if(nNumberOfDevices>0)
        {
            if( [UIAPPDELEGATE.BBBK length]>10 )
            {
                [self endProgress];
                [self openStreamingPage:UIAPPDELEGATE.BBBK bSockets:bSockets streamingType:streamingType];
                //[self openStreaming4VideoPageAfterAWhile:UIAPPDELEGATE.BBBK];
                return;
            }
        }

        if(nNumberOfDevices==1)
        {
            [self endProgress];
            //[self endProgressWithMessage:@"Connecting..."];
            Device *idev = [devicesArr objectAtIndex:0];
            NSString* BBBKID = idev.serialNo;
            [self openStreaming4VideoPageAfterAWhile:BBBKID];
        }
        else if(nNumberOfDevices>1)
        {
            [self endProgress];
            [self performSelector:@selector(showDevicesListForstreaming) withObject:nil afterDelay:.3];

         //   [self showDevicesListForstreaming];
        }
        else
            [self endProgressWithMessage:@"No devices information found!"];
    }
    else if([response rangeOfString:@"already"].location != NSNotFound)
    {
        /* UIAlertView *connAlert = [[UIAlertView alloc]initWithTitle:@"User Video" message:@"Manual video request already issued..please wait!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
         [connAlert show];
         [connAlert release];*/
        /*MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
         
         hud.mode = MBProgressHUDModeText;
         hud.labelText = @"Handling previous request.. please wait!";
         hud.margin = 10.f;
         hud.yOffset = 150.f;
         hud.removeFromSuperViewOnHide = YES;
         
         [hud hide:YES afterDelay:5];*/
        [self endProgressWithMessage:@"Handling previous request"];
    }
    else if([response rangeOfString:@"error"].location != NSNotFound)
    {
        /*  UIAlertView *connAlert = [[UIAlertView alloc]initWithTitle:@"User Video" message:@"Error requesting manual user video!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
         [connAlert show];
         [connAlert release];*/
        [self endProgressWithMessage:@"Error requesting a stream!"];
        return;
    }
    else 
    [self endProgress];
}

-(void) showDevicesListForstreaming
{
   /* UIPickerView* pickerView = [[UIPickerView alloc]initWithFrame:CGRectMake(0,150,320,430)];//to change the height
    pickerView.delegate =self;
    pickerView.dataSource =self;
    pickerView.showsSelectionIndicator = YES;
    [self.view addSubview:pickerView];*/
    [devices_picker reloadAllComponents];
    devices_picker.hidden = NO;
    return;
   /* popRect = CGRectMake(406, 110, 0, 0);
    CGRect pickerRect = CGRectMake(0, 10, 0, 0);
    
    NSArray *contents = [[NSArray alloc] initWithObjects:@"Besmella 1", @"Besmella 2", @"Besmella 3", nil];
    devicesPicker = [[DevicesPickerViewController alloc] init ];
     [devicesPicker setArray:contents inFrame:pickerRect];
    devicesPicker.delegatePicker = self;
    
    / *
    pickerPopOver = [[UIPopoverController alloc] initWithContentViewController:devicesPicker];
    pickerPopOver.popoverContentSize = CGSizeMake(320, 250);
    [pickerPopOver presentPopoverFromRect:popRect inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:TRUE];
    
    pOC = pickerPopOver;*/
    [self presentViewController:devicesPicker animated:YES completion:nil];

}

-(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]autorelease];
        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];
    }
}

-(void) parseUserVideoResponse:(NSString *)response
{
    NSLog(@"the response is %@",response);
    if([response rangeOfString:@"success"].location != NSNotFound)
    {
        /* UIAlertView *connAlert = [[UIAlertView alloc]initWithTitle:@"User Video" message:@"Manual video request issued!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
         [connAlert show];
         [connAlert release];*/
        //  MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        
        // Configure for text only and offset down
        /*      hud.mode = MBProgressHUDModeText;
         hud.labelText = @"Manual video request issued!";
         hud.margin = 10.f;
         hud.yOffset = 150.f;
         hud.removeFromSuperViewOnHide = YES;
         
         [hud hide:YES afterDelay:3];
         */
        [self endProgressWithMessage:@"Request Issued!"];
    }
    else if([response rangeOfString:@"already"].location != NSNotFound)
    {
        /* UIAlertView *connAlert = [[UIAlertView alloc]initWithTitle:@"User Video" message:@"Manual video request already issued..please wait!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
         [connAlert show];
         [connAlert release];*/
        /*MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
         
         hud.mode = MBProgressHUDModeText;
         hud.labelText = @"Handling previous request.. please wait!";
         hud.margin = 10.f;
         hud.yOffset = 150.f;
         hud.removeFromSuperViewOnHide = YES;
         
         [hud hide:YES afterDelay:5];*/
        [self endProgressWithMessage:@"Handling previous request"];
    }
    else if([response rangeOfString:@"error"].location != NSNotFound)
    {
        /*  UIAlertView *connAlert = [[UIAlertView alloc]initWithTitle:@"User Video" message:@"Error requesting manual user video!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
         [connAlert show];
         [connAlert release];*/
        [self endProgressWithMessage:@"Error connecting to device!"];
        return;
    }
}

-(void)addToDownloadBuffer:(NSString*) videoURL
{
    if([files_todownload count]>=20)
    {
        NSLog(@"Video buffering: download queue is full!");
        return;
    }
    
    NSString* local_file = [self getLocalFilePath: videoURL];
    if( [self isFilePathExists:local_file] )
    {
        NSLog(@"Video buffering: video downloaded before.. %@", videoURL);
        return;
    }
    if(local_file!=nil)
    {
        for(int t =0; t<[files_todownload count]; t++)
        {
            NSString* file_todownload = [files_todownload objectAtIndex:t];
            if([file_todownload isEqualToString:videoURL])
                return;
        }
        
        [files_todownload addObject:videoURL];
        NSLog(@"Video buffering: video added to download queue: %@", videoURL);
        
        return;
    }
    NSLog(@"Video buffering: error converting filename to local.. %@", videoURL);
}

- (void)startDownloadTask
{
	if (self.downloadTask1)
    {
        return;
    }
 	if([files_todownload count]<1)
    {
        NSLog(@"Video buffering: download queue is empty!");
        return;
    }
    /*
     Create a new download task using the URL session. Tasks start in the “suspended” state; to start a task you need to explicitly call -resume on a task after creating it.
     */
    NSString* DownloadURLString = [files_todownload objectAtIndex:0];
    NSURL *downloadURL = [NSURL URLWithString:DownloadURLString];
	NSURLRequest *request = [NSURLRequest requestWithURL:downloadURL];
	self.downloadTask1 = [self.session downloadTaskWithRequest:request];
    [self.downloadTask1 resume];
    
    //    self.imageView.hidden = YES;
    //   self.progressView.hidden = NO;
}


- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)downloadURL
{
    BLog();
    /*
     The download completed, you need to copy the file at targetPath before the end of this block.
     As an example, copy the file to the Documents directory of your app.
     */
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSArray *URLs = [fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
    NSURL *documentsDirectory = [URLs objectAtIndex:0];
    
    NSURL *originalURL = [[downloadTask originalRequest] URL];
    
    NSString* fileURL = [originalURL absoluteString];// [files_todownload objectAtIndex:0];
    NSString* downloadTo = [self getLocalFilePath:fileURL];
    
    // NSURL *destinationURL = [NSURL URLWithString:downloadTo];//[documentsDirectory URLByAppendingPathComponent:[originalURL lastPathComponent]];
    NSURL *destinationURL = [documentsDirectory URLByAppendingPathComponent:[downloadTo lastPathComponent]];
    
    NSError *errorCopy;
    NSLog(@"fileURL = %@.. calculated2= %@.. original request: %@", fileURL,destinationURL, [downloadTask originalRequest]);
    // For the purposes of testing, remove any esisting file at the destination.
    [fileManager removeItemAtURL:destinationURL error:NULL];
    BOOL success = [fileManager copyItemAtURL:downloadURL toURL:destinationURL error:&errorCopy];
    
    if (success)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            //   UIImage *image = [UIImage imageWithContentsOfFile:[destinationURL path]];
            //     self.imageView.image = image;
            //       self.imageView.hidden = NO;
            //        self.progressView.hidden = YES;
            BLog( @"File copied successfully to: %@", downloadTo );
            
            
            for(int t =0; t<[files_todownload count]; t++)
            {
                NSString* file_todownload = [files_todownload objectAtIndex:t];
                if([file_todownload isEqualToString:fileURL])
                {
                    [files_todownload removeObjectAtIndex:t];
                    t--;
                }
            }
        });
    }
    else
    {
        /*
         In the general case, what you might do in the event of failure depends on the error and the specifics of your application.
         */
        BLog(@"Error during the copy: %@", [errorCopy localizedDescription]);
    }
}

-(Boolean)isFilePathExists:(NSString*) local_filename
{
    NSFileManager* fileMgr = [NSFileManager defaultManager];
    BOOL fileExists = [fileMgr fileExistsAtPath:local_filename];
    return fileExists;
}

-(NSString*)getLocalFileName:(NSString*) videoURL
{
    if(videoURL == nil)
        return nil;
    
    NSString* local_filename = [[videoURL lowercaseString] stringByReplacingOccurrencesOfString:@"http://mialerts.info/vid_ftp/" withString:@"_"];
    local_filename = [local_filename stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
    //local_filename = [local_filename lowercaseString];
    NSLog(@"Local filename is %@", local_filename);
    
    return local_filename;
}

-(NSString*)getLocalFilePath:(NSString*) videoURL
{
    if(videoURL == nil)
        return nil;
    NSString* filename = [self getLocalFileName:videoURL];
    return [self getFullFilePath:filename];
}

-(NSString*)getFullFilePath:(NSString*) filename
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    if([paths count] > 0)
    {
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString* local_filename = [documentsDirectory stringByAppendingPathComponent:filename];
        
        NSLog(@"Video full path: %@", local_filename);
        return local_filename;
    }
    
    return filename;
}
#define BLog(formatString, ...) NSLog((@"%s " formatString), __PRETTY_FUNCTION__, ##__VA_ARGS__);

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    BLog();
    
    /*
     Report progress on the task.
     If you created more than one task, you might keep references to them and report on them individually.
     */
     
     if (downloadTask == self.downloadTask1)
     {
     double progress = (double)totalBytesWritten / (double)totalBytesExpectedToWrite;
     BLog(@"DownloadTask: %@ progress: %lf", downloadTask, progress);
     dispatch_async(dispatch_get_main_queue(), ^{
     //self.progressView.progress = progress;
     });
     }
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    BLog();
    
    if (error == nil)
    {
        NSLog(@"Task: %@ completed successfully", task);
    }
    else
    {
        NSLog(@"Task: %@ completed with error: %@", task, [error localizedDescription]);
    }
	
    //double progress = (double)task.countOfBytesReceived / (double)task.countOfBytesExpectedToReceive;
	dispatch_async(dispatch_get_main_queue(), ^{
		//self.progressView.progress = progress;
        [self startTownloadTaskAfterAWhile];
	});
    
    self.downloadTask1 = nil;
    // [self startTownloadTaskAfterAWhile];
    
}

-(void)startTownloadTaskAfterAWhile
{
    [self performSelector:@selector(startDownloadTask) withObject:nil afterDelay:3];
}

- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session
{
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    if (appDelegate.backgroundSessionCompletionHandler) {
        void (^completionHandler)() = appDelegate.backgroundSessionCompletionHandler;
        appDelegate.backgroundSessionCompletionHandler = nil;
        completionHandler();
    }
    
    NSLog(@"All tasks are finished");
}

-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
{
    BLog();
}

- (NSURLSession *)backgroundSession
{
    /*
     Using disptach_once here ensures that multiple background sessions with the same identifier are not created in this instance of the application. If you want to support multiple background sessions within a single process, you should create each session with its own identifier.
     */
     static NSURLSession *session2 = nil;
     static dispatch_once_t onceToken;
     dispatch_once(&onceToken, ^{
     NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:@"com.hegazy.iding.BackgroundTransfer.BackgroundSession"];
     session2 = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
     });
     return session2;
}

-(void)parseVideosResponse2:(NSString *)response :(NSURLConnection *)connection
{
    NSLog(@"the video parsing response is %@",response);
    if(response==nil && connection == nil)
    {
        // no buffered information
        //return;
        NSLog(@"No data in Buffer filename: %@", buffer_file_path);
        return;
    }
    else if([response rangeOfString:@"success"].location != NSNotFound)
    {
        
        XMLParser* xml = [[[XMLParser alloc] init]autorelease];
        if(TRUE/*self.isVideoList == TRUE || isVideoMuxList*/)
        {
            NSMutableDictionary* parsedDict = [[xml parseXML:response mainElement:@"video"] autorelease];
            [self parseDataWithDict:parsedDict :connection];
        }
        else
        {
            NSMutableDictionary* parsedDict = [xml parseXML:response mainElement:@"files"];
            [self parseDataWithDict:parsedDict :connection];
        };
        
        [self saveBuffer:response ];//]:@"videos_list"];
        
        // NSString *str = @"hello world";
        
        // [response writeToFile:buffer_file_path atomically:TRUE encoding:NSUTF8StringEncoding error:NULL];
    }
    else if(response!=nil && [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 :(NSURLConnection *)connection
{
    
    //if([connection.accessibilityHint isEqualToString:@"GetVideos"])
    
    if( TRUE )
    {
        NSMutableArray *parsedvalues = [responseDict objectForKey:@"Values"];
        int g = [parsedvalues count];
        NSMutableArray *finalParsedArr = [[[NSMutableArray alloc]init]autorelease];
        for (int k =0; k<g; k++) {
            VideosData *ivideo    = [[VideosData new]autorelease];;
            
            NSDictionary *d = [parsedvalues objectAtIndex:k];
            ivideo.videoName              = [d valueForKey:@"name"];
            ivideo.videoUrl     = [d valueForKey:@"url"];
            [self addToDownloadBuffer:ivideo.videoUrl];
            
            ivideo.camNo  = [d valueForKey:@"cam"];
            
            [finalParsedArr addObject:ivideo];
        }
        // uodate
        
       // self.tableData =[[NSMutableArray alloc]initWithArray:finalParsedArr];
        
       // [self.videosList reloadData];
        
       // [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:0.1];
        /* if([UIApplication sharedApplication].isNetworkActivityIndicatorVisible == TRUE)
         {
         [[UIApplication sharedApplication]setNetworkActivityIndicatorVisible:FALSE];
         }*/
        
    }

  //  [self startTownloadTaskAfterAWhile];

}

-(void)saveBuffer:(NSString *)str //:(NSString *)file_name
{
  //  BOOL isVideoMuxList = true;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *buffer_filename = [NSString stringWithFormat:@"video_list_buffer-%@.xml", UIAPPDELEGATE.loggedUserName/*, (isVideoMuxList?1:0)*/];
    buffer_file_path = [documentsDirectory stringByAppendingPathComponent:buffer_filename];
    
    NSLog(@"Buffer filename: %@", buffer_file_path);
    
    
    // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    //   NSString *documentsDirectory = [paths objectAtIndex:0];
    //   NSString *filePath = [documentsDirectory stringByAppendingPathComponent:file_name];
    
    // NSString *str = @"hello world";
    
    [str writeToFile:buffer_file_path atomically:TRUE encoding:NSUTF8StringEncoding error:NULL];
}

-(void)callWSForVideos
{
    if(![self isVisible])
    {
        if(UIAPPDELEGATE.isAutoUpdate)
            [self callWSAfterAWhile];
        return;
    }
    if(self.mutableDataVideos!=nil)
    {
        self.mutableDataVideos=nil;
    }
    self.mutableDataVideos = [NSMutableData data];
    //http://mocal.mobi/listAlerts.php?username=whiletrue@hotmail.com&password=123
    //NSString *deviceId = [[UIDevice currentDevice]uniqueIdentifier];

    NSString *loginUrl = [NSString stringWithFormat:@"http://mialerts.info/getVideos.php?username=%@&password=%@",  UIAPPDELEGATE.loggedUserName,  UIAPPDELEGATE.loggedPassword];

    NSURL *url = [NSURL URLWithString:loginUrl];
    NSMutableURLRequest *urlRequest = [[[NSMutableURLRequest alloc]initWithURL:url]autorelease];
    if(self.urlConnectionBufferVideos != nil)
    {
        [self.urlConnectionBufferVideos release];
        self.urlConnectionBufferVideos = nil;
    }

    self.urlConnectionBufferVideos = [[NSURLConnection alloc]initWithRequest:urlRequest delegate:self];
    [self.urlConnectionBufferVideos setAccessibilityHint:@"GetVideos"];
    
    // self.session = [self backgroundSession];
}

// returns the number of 'columns' to display.
- (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];
    [self performSelector:@selector(openStreamingPage4:) withObject:BBBKID afterDelay:0.1];
}

@end
