//
//  VideosMuxListViewController.m
//  MiAlerts
//
//  Created by MacBook Pro on 23/09/13.
//  Copyright (c) 2013 Mahammad. All rights reserved.
//

#import "VideosMuxListViewController.h"
#import "VideoPlayViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "EGORefreshTableHeaderView.h"

@interface VideosMuxListViewController ()

@end

@implementation VideosMuxListViewController
@synthesize mutableData,urlConnection,tableData,mp4UrlLink,smallMP4UrlLink,isVideoList;

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

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"Videos Mux";
    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 callWSForVideos];
}

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

-(void)callWSForVideos
{
    self.isVideoList = TRUE;
    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 *loginUrl = [NSString stringWithFormat:@"http://mialerts.info/getVideos.php?username=%@&password=%@",  UIAPPDELEGATE.loggedUserName,  UIAPPDELEGATE.loggedPassword];
    NSLog(@"Videos list is at %@", loginUrl );

    
    NSURL *url = [NSURL URLWithString:loginUrl];
    NSMutableURLRequest *urlRequest = [[[NSMutableURLRequest alloc]initWithURL:url]autorelease];
    if(self.urlConnection != nil)
    {
        [self.urlConnection release];
        self.urlConnection = nil;
    }
    
    [self.urlConnection setAccessibilityHint:@"GetVideos"];
    self.urlConnection = [[NSURLConnection alloc]initWithRequest:urlRequest delegate:self];

}

#pragma mark NSURLConnection Delegates
#pragma mark Connection callbacks

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    //
	[self.mutableData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	[self.mutableData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"error");
    UIAlertView *connAlert = [[UIAlertView alloc]initWithTitle:@"Error" message:[error description] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [connAlert show];
    [connAlert release];
    
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *response = [[NSString alloc]initWithData:self.mutableData encoding:NSASCIIStringEncoding];
   // NSLog(@"the response is %@",response);
    
    
    [self parseVideosResponse:response :connection];
}

-(void)parseVideosResponse:(NSString *)response :(NSURLConnection *)connection
{
    
    //NSLog(@"the response is %@",response);
    if([response rangeOfString:@"success"].location != NSNotFound)
    {
        
        XMLParser* xml = [[XMLParser alloc] init];
        if(self.isVideoList == TRUE)
        {
            NSMutableDictionary* parsedDict = [xml parseXML:response mainElement:@"video"];
            [self parseDataWithDict:parsedDict :connection];
        }
        else
        {
            NSMutableDictionary* parsedDict = [xml parseXML:response mainElement:@"files"];
            [self parseDataWithDict:parsedDict :connection];
        }
        
        
    }
    else if([response rangeOfString:@"error"].location != NSNotFound)
    {
        UIAlertView *connAlert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"something went wrong" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [connAlert show];
        [connAlert release];
    }
    
    [HUD hide:YES];
    [HUD removeFromSuperview];
    HUD = nil;
}

-(void)parseDataWithDict:(NSMutableDictionary *)responseDict :(NSURLConnection *)connection
{
     
    //if([connection.accessibilityHint isEqualToString:@"GetVideos"])
    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++) {
            
            
            
            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"];
            
            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;
            
            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;
          
                    if(cam==1)
                        vid.mux_cams_urls1 = videoUrl;
                    else if(cam==2)
                        vid.mux_cams_urls2 = videoUrl;
                    else if(cam==3)
                        vid.mux_cams_urls3 = videoUrl;
                    else
                        vid.mux_cams_urls0 = videoUrl;
                    
                    vid.total_cams++;
                    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 = 1;
                [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"])
    {
        NSMutableArray *parsedvalues = [responseDict objectForKey:@"Values"];
        int g = [parsedvalues count];
        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];
        }*/
        
    
    }
    
    [HUD hide:YES];
    [HUD removeFromSuperview];
    HUD = nil;

    
}

-(void)PlayVideoURL:(NSString *)videoMP4URL
{
    MPMoviePlayerViewController *player = [[MPMoviePlayerViewController alloc]initWithContentURL:[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];
    
    leftIdLBL.text       =  [NSString stringWithFormat:@"%ld", d.total_cams];//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;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
    VideosData *selectedVideo= [self.tableData objectAtIndex:indexPath.row];
    [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.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.mobi/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];
    
}
#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 {
    [_videosList release];
    [super dealloc];
}
- (void)viewDidUnload {
    [self setVideosList:nil];
    _refreshHeaderView = nil;
    [super viewDidUnload];
}
@end
