//
//  VideosListViewController.m
//  iDing
//
//  Created by MacBook Pro on 23/09/13.
//  Copyright (c) 2013 mahammad. All rights reserved.
//

#import "VideosListViewController.h"
#import "VideoPlayViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "EGORefreshTableHeaderView.h"
#import "FourVideosViewController.h"

@interface VideosListViewController ()

@end

@implementation VideosListViewController
@synthesize mutableData,urlConnection,tableData,mp4UrlLink,smallMP4UrlLink,isVideoList,isVideoMuxList,buffer_file_path,previous_response;

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

- (void)viewDidLoad
{
    [super viewDidLoad];
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7)
    {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }

    // Do any additional setup after loading the view from its nib.
    self.title = @"Videos";
    self.isVideoList = FALSE;
    if(_refreshHeaderView == nil)
    {
        EGORefreshTableHeaderView *view = [[EGORefreshTableHeaderView alloc]initWithFrame:CGRectMake(0.0f, 0.0f-self.videosList.bounds.size.height, self.view.frame.size.width, self.videosList.bounds.size.height)];
        view.delegate = self;
        [self.videosList addSubview:view];
        _refreshHeaderView = view;
        [view release];
    }
    
    //update the last update date
    [_refreshHeaderView refreshLastUpdatedDate];
   
    [self reloadTableVIew];
    
    UIBarButtonItem * doneButton =
    [[UIBarButtonItem alloc]
     initWithBarButtonSystemItem:UIBarButtonSystemItemTrash
     target:self
     action:@selector( removeAllVideos ) ];
    
    self.navigationItem.rightBarButtonItem = doneButton ; // not it..
    
    [doneButton release] ;

    previous_response = @"";
    [ self loadBufferedList ];
    [ self startAutoUpdateTimer ];

 //   [self callWSForVideos];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [self.videosList setDelegate:self];
    [self.videosList setDataSource:self];
    //[[UIApplication sharedApplication]setNetworkActivityIndicatorVisible:TRUE];
    
}

-(void)callWSForVideos:(BOOL)bMux :(BOOL)autoRefersh
{
    if(bMux)
        isVideoMuxList = TRUE;
    else
        isVideoList = TRUE;
 //   files_todownload = [[NSMutableArray alloc]init];

    if(HUD!=nil)
        return;// some other command is running
    
    HUD = [[MBProgressHUD alloc]initWithView:self.view];
    HUD.delegate = self;
    HUD.mode = MBProgressHUDModeIndeterminate;
    HUD.labelText = @"Loading...";
    [self.navigationController.view.superview addSubview:HUD];
    if(!autoRefersh)
        [HUD show:YES];

    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://mialerts.info/getVideos.php?username=%@&password=%@",  UIAPPDELEGATE.loggedUserName,  UIAPPDELEGATE.loggedPassword];
    NSURL *url = [NSURL URLWithString:loginUrl];
    NSMutableURLRequest *urlRequest = [[[NSMutableURLRequest alloc]initWithURL:url]autorelease];
    if(self.urlConnection != nil)
    {
        [self.urlConnection release];
        self.urlConnection = nil;
    }
    self.urlConnection = [[NSURLConnection alloc]initWithRequest:urlRequest delegate:self];

    [self.urlConnection setAccessibilityHint:@"GetVideos"];

    
   // self.session = [self backgroundSession];
}

-(void)loadBufferedList
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    if([paths count] > 0)
    {
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *buffer_filename = [NSString stringWithFormat:@"video_list_buffer-%@.xml", UIAPPDELEGATE.loggedUserName/*, (bMux?1:0)*/];
        buffer_file_path = [documentsDirectory stringByAppendingPathComponent:buffer_filename];
        
        NSLog(@"Buffer filename: %@", buffer_file_path);
        NSString *response_bufferred = [NSString stringWithContentsOfFile:buffer_file_path encoding:NSUTF8StringEncoding error:NULL];
        [self parseVideosResponse:response_bufferred :nil];
    }
}

-(void)callWSForRemoveAllVideos
{
    if(HUD!=nil)
    {
        [HUD hide:YES];
        [HUD removeFromSuperview];
        HUD = nil;
    }
    
    HUD = [[MBProgressHUD alloc]initWithView:self.view];
    HUD.delegate = self;
    HUD.mode = MBProgressHUDModeIndeterminate;
    HUD.labelText = @"Deleting...";

    [self.navigationController.view.superview addSubview:HUD];
    [HUD show:YES];
    
    NSString *url_string = [NSString stringWithFormat:@"http://mialerts.info/removeAllVideos.php?username=%@&password=%@",  UIAPPDELEGATE.loggedUserName,  UIAPPDELEGATE.loggedPassword];
    NSURL *url = [NSURL URLWithString:url_string];
    NSMutableURLRequest *urlRequest = [[[NSMutableURLRequest alloc]initWithURL:url]autorelease];
    if(self.urlConnection != nil)
    {
        [self.urlConnection release];
        self.urlConnection = nil;
    }
    
    [self.urlConnection setAccessibilityHint:@"RemoveAllVideos"];
    self.urlConnection = [[NSURLConnection alloc]initWithRequest:urlRequest delegate:self];
}

-(void) removeAllVideos
{
    if([self.tableData count]<1)
        return;

    if(HUD!=nil)
        return;// some other command is running

    UIAlertView *connAlert = [[UIAlertView alloc]initWithTitle:@"Warning" message:@"Are you sure you want to delete all videos?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Yes", nil];
    [connAlert setTag:3];
    [connAlert show];
    [connAlert release];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 3) { // UIAlertView with tag 2 detected
        if (buttonIndex == 0)
        {
            NSLog(@"user pressed Button Indexed 0");
           
        }
        else
        {
            NSLog(@"user pressed Button Indexed 1");
            [ self callWSForRemoveAllVideos ];
          

            // Any action can be performed here
        }
    }
}

-(void) removeAllVideosWork
{
    [self.tableData removeAllObjects];

    [self removeBuffer:false];//(BOOL)isVideoMuxListParam //:(NSString *)file_name
    [self removeBuffer:TRUE];//(BOOL)isVideoMuxListParam //:(NSString *)file_name

    [self reloadTableViewDataSource];
}

#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];
    [self performSelector:@selector(startAutoUpdateTimer) withObject:NULL afterDelay:2];
}

- (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];*/
    
    if(HUD!=nil)
    {
        [HUD hide:YES];
        [HUD removeFromSuperview];
        HUD = nil;
    }
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    // Configure for text only and offset down
    hud.mode = MBProgressHUDModeText;
    hud.labelText = @"Network Error!";
    hud.margin = 10.f;
    hud.yOffset = 150.f;
    hud.removeFromSuperViewOnHide = YES;
    
    [hud hide:YES afterDelay:3];
    [self performSelector:@selector(startAutoUpdateTimer) withObject:NULL afterDelay:5];
}

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

-(void)saveBuffer:(NSString *)str //:(NSString *)file_name
{
    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)removeBuffer:(BOOL)isVideoMuxListParam //:(NSString *)file_name
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *buffer_filename = [NSString stringWithFormat:@"video_list_buffer-%@.xml", UIAPPDELEGATE.loggedUserName/*, (isVideoMuxListParam?1:0)*/];
    buffer_file_path = [documentsDirectory stringByAppendingPathComponent:buffer_filename];
    
    NSLog(@"Buffer filename to remove: %@", buffer_file_path);
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager removeItemAtPath:buffer_file_path error:NULL];
}

-(void)parseVideosResponse:(NSString *)response :(NSURLConnection *)connection
{
    NSLog(@"the video parsing response is %@",response);
    if(HUD!=nil)
    {
        [HUD hide:YES];
        [HUD removeFromSuperview];
        HUD = nil;
    }
    if(response==nil && connection == nil)
    {
        // no buffered information
        //return;
        NSLog(@"No data in Buffer filename: %@", buffer_file_path);
        return;
    }
    else if(response!=nil && previous_response != nil && [previous_response length]>10 && [response isEqualToString:previous_response])
    {
        NSLog(@"same response.. nothing changed!");// will never come here as timestamps changes over time
        return;
    }
    else if( [[connection accessibilityHint] isEqualToString:@"RemoveAllVideos"] && [response rangeOfString:@"success"].location != NSNotFound)
    {
          [self removeAllVideosWork];
    }
    else if([response rangeOfString:@"success"].location != NSNotFound)
    {
        
        XMLParser* xml = [[XMLParser alloc] init];
        if(self.isVideoList == TRUE || isVideoMuxList)
        {
            NSMutableDictionary* parsedDict = [xml parseXML:response mainElement:@"video"];
            [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];
    }

    previous_response = [response mutableCopy];
}

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

-(void)doFilesFetch
{
    if ([NSURLSession class]) {
        // Create a background session and enqueue transfers
    }
    else {
        NSLog(@"NSURLSession IS NOT SUPPORTED");
    }
}

-(Boolean)isFileExists:(NSString*) filename
{
    NSString* local_filename = [self getFullFilePath:filename];
    return [self isFilePathExists:local_filename];
}

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

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


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

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

/*
-(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)parseDataWithDict:(NSMutableDictionary *)responseDict :(NSURLConnection *)connection
{
     
    //if([connection.accessibilityHint isEqualToString:@"GetVideos"])
    if(self.isVideoMuxList == TRUE)
    {
        NSMutableArray *parsedvalues = [responseDict objectForKey:@"Values"];
        int g = [parsedvalues count];
        NSMutableArray *finalParsedArr = [[NSMutableArray alloc]init];
        for (int k =0; k<g; k++) {
            NSDictionary *d = [parsedvalues objectAtIndex:k];
            NSString* videoName              = [d valueForKey:@"name"];
            NSString* videoUrl     = [d valueForKey:@"url"];
            NSString* camNo  = [d valueForKey:@"cam"];
            NSString* timeStamp  = [d valueForKey:@"timestamp"];
            
            //[self addToDownloadBuffer:videoUrl];
            
            NSArray* tokens = [videoUrl componentsSeparatedByString:@"_"];
            //NSLog(@"URL: %@, tokens are %d", videoUrl, [tokens count] );
            
            if([tokens count]>3)
            {
                camNo  = [tokens objectAtIndex:2];// valueForKey:@"timestamp"];
                NSString* timeStampToken  = [tokens objectAtIndex:3];// valueForKey:@"timestamp"];
                tokens = [timeStampToken componentsSeparatedByString:@"."];
                
                timeStamp  = [tokens objectAtIndex:0];// valueForKey:@"timestamp"];
                
                NSLog(@"URL: %@, timestamp is %@.. cam %@", videoUrl, timeStamp, camNo);
                
            }
            long timestamp = [timeStamp longLongValue];
            long cam = [camNo longLongValue];
            
            Boolean bFound = false;
            VideosData *vidSelected = nil;
            
            int finalCount = [finalParsedArr count];
            for (int k2 =finalCount-1; k2>=0; k2--) {
                VideosData *vid = [finalParsedArr objectAtIndex:k2];
                
                int nDiff = abs(timestamp - [vid timestamp]);
                //  NSLog( @"nDiff=%d", nDiff );
                
                if( nDiff<35)
                {
                    NSLog( @"nDiff=%d", nDiff );
                    bFound = true;
                    vidSelected = vid;
                    break;
                }
            }

            if(!bFound)
            {
                VideosData *ivideo    = [VideosData new];
                ivideo.videoName              = videoName;
                ivideo.videoUrl     = videoUrl;
                ivideo.camNo  = camNo;
                ivideo.timestamp     = timestamp;
                ivideo.cam  = cam;
                ivideo.total_cams = 0;
                [finalParsedArr addObject:ivideo];
           
                vidSelected = ivideo;
            
            }
            
            if(cam==1)
            {
                if(vidSelected.mux_cams_urls1!=NULL)
                    NSLog( @"cam %ld is already %@... want to set it to %@", cam, vidSelected.mux_cams_urls1, videoUrl );
                vidSelected.mux_cams_urls1 = videoUrl;
            }
            else if(cam==2)
            {
                if(vidSelected.mux_cams_urls2!=NULL)
                    NSLog( @"cam %ld is already %@... want to set it to %@", cam, vidSelected.mux_cams_urls2, videoUrl );
                vidSelected.mux_cams_urls2 = videoUrl;
            }
            else if(cam==3)
            {
                if(vidSelected.mux_cams_urls3!=NULL)
                    NSLog( @"cam %ld is already %@... want to set it to %@", cam, vidSelected.mux_cams_urls3, videoUrl );
                vidSelected.mux_cams_urls3 = videoUrl;
            }
            else
            {
                if(vidSelected.mux_cams_urls0!=NULL)
                    NSLog( @"cam %ld is already %@... want to set it to %@", cam, vidSelected.mux_cams_urls0, videoUrl );
                vidSelected.mux_cams_urls0 = videoUrl;
            }

            vidSelected.total_cams++;
        }
        // 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];
         }*/
    }
    else if( self.isVideoList == TRUE )
    {
        NSMutableArray *parsedvalues = [responseDict objectForKey:@"Values"];
        int g = [parsedvalues count];
        NSMutableArray *finalParsedArr = [[NSMutableArray alloc]init];
        for (int k =0; k<g; k++) {
            VideosData *ivideo    = [VideosData new];

            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];
        }*/

    }
    else //if([connection.accessibilityHint isEqualToString:@"GetMP4"])
    {
        NSLog( @"processing files" );
        NSMutableArray *parsedvalues = [responseDict objectForKey:@"Values"];
        int g = [parsedvalues count];

        NSLog( @"the video count is %d", g );

        for (int k =0; k<g; k++) {
            
            NSDictionary *dict =[parsedvalues objectAtIndex:k];
            self.mp4UrlLink = [dict valueForKey:@"mp4"];
            self.smallMP4UrlLink = [dict valueForKey:@"small"];
        }
        // uodate

        [self PlayVideoURL:self.mp4UrlLink];
        
       /* if([UIApplication sharedApplication].isNetworkActivityIndicatorVisible == TRUE)
        {
            [[UIApplication sharedApplication]setNetworkActivityIndicatorVisible:FALSE];
        }*/
        
    
    }
  //  [self startTownloadTaskAfterAWhile];
    if(connection!=nil && HUD!=nil)
    {
        [HUD hide:YES];
        [HUD removeFromSuperview];
        HUD = nil;
    }
}

-(void)PlayVideoURL:(NSString *)videoMP4URL
{
    NSURL* url = [self getShortURL:videoMP4URL];
    
    
    MPMoviePlayerViewController *player = [[MPMoviePlayerViewController alloc]initWithContentURL:url/*[NSURL URLWithString:videoMP4URL]*/];
    [self presentMoviePlayerViewControllerAnimated:player];
    [player.moviePlayer play];
}

#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 [self.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, 10, 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, 10, 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];

        [idLabel     release];
        [iTitle      release];
        [iTimeStamp  release];
	}

	// Configure cell
    NSUInteger row = [indexPath row];
	//alert_types_id,device_title,update_timestamp
	// Sets the text for the cell
    VideosData *d = [self.tableData objectAtIndex:row];
    UILabel *leftIdLBL          = (UILabel *)[cell viewWithTag:4000];
    UILabel *topTitleLBL        = (UILabel *)[cell viewWithTag:4001];
    //UILabel *btmTimeStampLBL    = (UILabel *)[cell viewWithTag:4002];

    if(isVideoMuxList)
        leftIdLBL.text       =  [NSString stringWithFormat:@"%ld", d.total_cams];//d.camNo;
	else
        leftIdLBL.text       =  d.camNo;
    topTitleLBL.text     = 	d.videoName;
   // btmTimeStampLBL.text =  d.videoUrl;
    //impactLBL.text       =  [NSString stringWithFormat:@"Impact Level : %@",d.impactLevel];
	cell.accessoryType   = UITableViewCellAccessoryDisclosureIndicator;
	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;
}

-(NSString*)getShortPath:(NSString*) videoURL
{
    NSString* local_file = [self getLocalFilePath: videoURL];
    if( [self isFilePathExists:local_file] )
    {
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSArray *URLs = [fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
        NSURL *documentsDirectory = [URLs objectAtIndex:0];
        NSURL *destinationURL = [documentsDirectory URLByAppendingPathComponent:[local_file lastPathComponent]];
        return [destinationURL absoluteString];
    }
    return videoURL;
}

-(NSURL*)getShortURL:(NSString*) videoURL
{
    NSString* local_file = [self getLocalFilePath: videoURL];
    if(![ self isFilePathExists:local_file ])
        return [NSURL URLWithString:videoURL];

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *URLs = [fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
    NSURL *documentsDirectory = [URLs objectAtIndex:0];
    NSURL *destinationURL = [documentsDirectory URLByAppendingPathComponent:[local_file lastPathComponent]];
    return destinationURL;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    VideosData *selectedVideo= [self.tableData objectAtIndex:indexPath.row];
    if(isVideoMuxList)
    {
        FourVideosViewController *dv = [[FourVideosViewController alloc]initWithNibName:@"FourVideosViewController" bundle:nil];
       
        dv.mux_cams_urls0 = [self getShortPath:selectedVideo.mux_cams_urls0];
        dv.mux_cams_urls1 = [self getShortPath:selectedVideo.mux_cams_urls1];
        dv.mux_cams_urls2 = [self getShortPath:selectedVideo.mux_cams_urls2];
        dv.mux_cams_urls3 = [self getShortPath:selectedVideo.mux_cams_urls3];
        
        [self.navigationController pushViewController:dv animated:YES];
        
        return;
    }

    [self getMovieMP4URL:selectedVideo.videoUrl];
    
    
    /*VideoPlayViewController *ivideo = [[VideoPlayViewController alloc]initWithNibName:@"VideoPlayViewController" bundle:nil];
    ivideo.vda = selectedVideo;
    [self.navigationController pushViewController:ivideo animated:YES];*/
   /* NSString *url = selectedVideo.videoUrl;
    url = [url stringByReplacingOccurrencesOfString:@"h264" withString:@"mpeg"];
    MPMoviePlayerViewController *player = [[MPMoviePlayerViewController alloc]initWithContentURL:[NSURL URLWithString:url]];
    [self presentMoviePlayerViewControllerAnimated:player];
    [player.moviePlayer play];*/
    
}

-(void)getMovieMP4URL:(NSString *)videoUrl
{
    [self PlayVideoURL:videoUrl];
    return;
    
    self.isVideoList = FALSE;
    HUD = [[MBProgressHUD alloc]initWithView:self.view];
    HUD.delegate = self;
    HUD.mode = MBProgressHUDModeIndeterminate;
    HUD.labelText = @"Loading...";
    [self.navigationController.view.superview addSubview:HUD];
    [HUD show:YES];
    
    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 *movieURl = [NSString stringWithFormat:@"http://mialerts.info/getVideoShort.php?url=%@",videoUrl];
    NSURL *url = [NSURL URLWithString:movieURl];
    NSMutableURLRequest *urlRequest1 = [[[NSMutableURLRequest alloc]initWithURL:url]autorelease];
    if(self.urlConnection != nil)
    {
        [self.urlConnection release];
        self.urlConnection = nil;
    }
    
    [self.urlConnection setAccessibilityHint:@"GetMP4"];
    self.urlConnection = [[NSURLConnection alloc]initWithRequest:urlRequest1 delegate:self];
}

-(void)playerItemDidReachEnd:(AVPlayer *)player
{
    NSLog(@"reached end");
}
#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
	
    // NSLog(@"scrollViewDidScroll");
	[_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    
}




#pragma mark
#pragma mark UIScrollViewDelegate methods
#pragma mark


// Load images for only that are visible cells

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    
    if(UIAPPDELEGATE.pullforRefresh == TRUE)
    {
        //NSLog(@"egoRefreshScrollViewDidEndDragging");
        [_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    }
}


-(void)reloadTableVIew
{
    [self callWSForVideos:isVideoMuxList :FALSE];
}
#pragma mark -
#pragma mark Data Source Loading / Reloading Methods

- (void)reloadTableViewDataSource
{
	
	//  should be calling your tableviews data source model to reload
	//  put here just for demo
    
	_reloading = YES;
    
    [self reloadTableVIew];
	
}

- (void)doneLoadingTableViewData{
	
	//  model should call this when its done loading
	_reloading = NO;
	[_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.videosList];
}


#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view
{
    [self reloadTableViewDataSource];
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	
	return _reloading; // should return if data source model is reloading
	
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
	
	return [NSDate date]; // should return date data source was last changed
	
}


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

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

    [_videosList release];
    [super dealloc];
}
- (void)viewDidUnload {
    [self setVideosList:nil];
    _refreshHeaderView = nil;
    [super viewDidUnload];
}
/*

- (void)startDownloadTask
{
	if (self.downloadTask)
    {
        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.downloadTask = [self.session downloadTaskWithRequest:request];
    [self.downloadTask resume];
    
//    self.imageView.hidden = YES;
 //   self.progressView.hidden = NO;
}
*/
/*
- (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 *session = nil;
	static dispatch_once_t onceToken;
	dispatch_once(&onceToken, ^{
		NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:@"com.example.apple-samplecode.SimpleBackgroundTransfer.BackgroundSession"];
		session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
	});
	return session;
}
/*
#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.downloadTask)
    {
        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 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]);
    }
}
* /
- (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.downloadTask = nil;
   // [self startTownloadTaskAfterAWhile];
    
}

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

/*
 If an application has received an -application:handleEventsForBackgroundURLSession:completionHandler: message, the session delegate will receive this message to indicate that all messages previously enqueued for this session have been delivered. At this time it is safe to invoke the previously stored completion handler, or to begin any internal updates that will result in invoking the completion handler.
 * /
- (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();
}
 */


@end
