//
//  Copyright (c) 2013-2016 Cédric Luthi. All rights reserved.
//

#define SYSTEM_VERSION_EQUAL_TO(v)                  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v)              ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v)     ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)

#import "ThirdViewController.h"

#import "XCDYouTubeKit/XCDYouTubeKit.h"

#import "MPMoviePlayerController+BackgroundPlayback.h"

#import "searchResultTableCell.h"

#import <AssetsLibrary/ALAsset.h>

#import "DBManager.h"

#import "Operation.h"

@interface ThirdViewController ()
@property (nonatomic, weak) id<XCDYouTubeOperation> videoOperation;
@property (nonatomic, strong) NSMutableArray *arrResult;
@end

@implementation ThirdViewController {
    UIView *_mask;
}

- (void) viewDidLoad
{
    [super viewDidLoad];
    self.tblResult.estimatedRowHeight = 64;
    // Do any additional setup after loading the view, typically from a nib.
    
    self.tblResult.delegate = self;
    self.tblResult.dataSource = self;
    
    self.arrResult = [[NSMutableArray alloc] init];
    
    //[yourTextField setDelegate:self];
    self.txtSearch.delegate = self;
    
    self.selectionEnabled = 1;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == self.txtSearch) {
        [textField resignFirstResponder];
        [self.view endEditing:YES];
        
        NSString * stringSearch = [_txtSearch text];
        /*
        [[Operation sharedOperation] search:stringSearch
                                    success:^(id JSON) {
                                        NSLog(@"DONE!");
                                        [self populateResult:JSON];
                                    } failure:^(NSError *error, id JSON) {
                                        NSLog(@"FAIL!");
                                    }];
        */
        
        
        
        [self.arrResult removeAllObjects];
        
        NSMutableArray *detailList = [[NSMutableArray alloc] init];
        
        NSString *valueIdVideoId = stringSearch;
        NSLog(@"%@",valueIdVideoId);
        
        [detailList addObject:valueIdVideoId];

        [self getDetail:detailList];

        
        
        return NO;
    }
    return YES;
}

- (void)getDetail:(NSArray *) detailList {
    [[Operation sharedOperation] details:detailList
                                 success:^(id JSON) {
                                     NSLog(@"DONE!");
                                     [self populateDetail:JSON];
                                 } failure:^(NSError *error, id JSON) {
                                     NSLog(@"FAIL!");
                                 }];
}

- (void)getVideoInfo:(NSString *) videoId {
    [[Operation sharedOperation] getVideoInfo:videoId
                                      success:^(id JSON) {
                                          NSLog(@"DONE!");
                                      } failure:^(NSError *error, id JSON) {
                                          NSLog(@"FAIL!");
                                      }];
}

- (void)populateResult:(NSDictionary *) result {
    NSLog(@"result: %@", result);
    
    if([result valueForKey:@"items"]) {
        [self.arrResult removeAllObjects];
        
        NSDictionary *selectedKey = [result valueForKey:@"items"];
        NSMutableArray *detailList = [[NSMutableArray alloc] init];
        
        for(id key in selectedKey) {
            NSDictionary *selectedSubKey = [key valueForKey:@"id" ];
            NSString *valueIdKind = [selectedSubKey objectForKey:@"kind"];
            NSString *valueIdVideoId = [selectedSubKey objectForKey:@"videoId"];
            NSString *valueKind = [key objectForKey:@"kind"];
            NSLog(@"%@ %@ %@",valueKind, valueIdKind, valueIdVideoId);
            
            [detailList addObject:valueIdVideoId];
        }
        [self getDetail:detailList];
    }
}

- (void)populateDetail:(NSDictionary *) result {
    if([result valueForKey:@"items"]) {
        NSDictionary * selectedKey = [result valueForKey:@"items"];
        
        for(id key in selectedKey) {
            NSString * valueId = [key objectForKey:@"id"];
            NSString * valueKind = [key objectForKey:@"kind"];
            NSString * valueDefinition = [[key objectForKey:@"contentDetails"] objectForKey:@"definition"];
            NSString * valueDuration = [[key objectForKey:@"contentDetails"] objectForKey:@"duration"];
            
            NSString * valueChannelId = [[key objectForKey:@"snippet"] objectForKey:@"channelId"];
            NSString * valueChannelTitle = [[key objectForKey:@"snippet"] objectForKey:@"channelTitle"];
            
            NSString * valueThumbnailUrl = [[[[key objectForKey:@"snippet"] objectForKey:@"thumbnails"] objectForKey:@"default"] objectForKey:@"url"];
            NSString * valueTitle = [[key objectForKey:@"snippet"] objectForKey:@"title"];
            NSString * valueDislikeCount = [[key objectForKey:@"statistics"] objectForKey:@"dislikeCount"];
            NSString * valueLikeCount = [[key objectForKey:@"statistics"] objectForKey:@"likeCount"];
            NSString * valueViewCount = [[key objectForKey:@"statistics"] objectForKey:@"viewCount"];
            
            
            NSMutableDictionary * newDict = [NSMutableDictionary dictionary];
            [newDict setObject:valueId forKey:@"id"];
            [newDict setObject:valueKind forKey:@"kind"];
            [newDict setObject:valueDefinition forKey:@"definition"];
            [newDict setObject:valueDuration forKey:@"duration"];
            [newDict setObject:valueThumbnailUrl forKey:@"thumbnailUrl"];
            [newDict setObject:valueTitle forKey:@"title"];
            
            [newDict setObject:valueChannelId forKey:@"channelId"];
            [newDict setObject:valueChannelTitle forKey:@"channelTitle"];
            
            if(valueDislikeCount != nil)
                [newDict setObject:valueDislikeCount forKey:@"dislikeCount"];
            else
                [newDict setObject:@"0" forKey:@"dislikeCount"];
            
            if(valueLikeCount != nil)
                [newDict setObject:valueLikeCount forKey:@"likeCount"];
            else
                [newDict setObject:@"0" forKey:@"likeCount"];
            
            if(valueViewCount != nil)
                [newDict setObject:valueViewCount forKey:@"viewCount"];
            else
                [newDict setObject:@"0" forKey:@"viewCount"];
            
            
            [[Operation sharedOperation] getImage:valueThumbnailUrl
                                          success:^(id JSON) {
                                              NSLog(@"DONE!");
                                              [self insertImage:JSON dictionary:newDict];
                                          } failure:^(NSError *error, id JSON) {
                                              NSLog(@"FAIL!");
                                          }];
            
            /*
             NSString *imageUrlString = valueThumbnailUrl;
             NSURL *url = [NSURL URLWithString:imageUrlString];
             NSData *data = [[NSData alloc] initWithContentsOfURL:url];
             UIImage *image = [UIImage imageWithData:data];
             if(image) {
             [newDict setObject:image forKey:@"thumbnailData"];
             }
             */
            [self.arrResult addObject:newDict];
        }
        [self.tblResult reloadData];
    }
    
}

-(void)insertImage:(NSData *)image dictionary:(NSMutableDictionary *)dictionary {
    if(image) {
        //UIImage * image = [UIImage imageWithData:imageData];
        [dictionary setObject:image forKey:@"thumbnailObject"];
        [self.tblResult reloadData];
    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.arrResult.count;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"searchResultTableCell";
    
    searchResultTableCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        // Load the top-level objects from the custom cell XIB.
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil];
        // Grab a pointer to the first object (presumably the custom cell, as that's all the XIB should contain).
        cell = [topLevelObjects objectAtIndex:0];
    }
    
    if (cell == nil)
    {
        cell = [[searchResultTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    // Set the loaded data to the appropriate cell labels.
    cell.textLabel.text = [NSString stringWithFormat:@"%@", [[self.arrResult objectAtIndex:indexPath.row] valueForKey:@"title"]];
    
    //cell.detailTextLabel.text = [NSString stringWithFormat:@"%@", [[self.arrResult objectAtIndex:indexPath.row] valueForKey:@"id"]];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@", [[self.arrResult objectAtIndex:indexPath.row] valueForKey:@"channelTitle"]];
    
    //int duration = [[[self.arrResult objectAtIndex:indexPath.row] valueForKey:@"duration"] intValue];
    //cell.duration.text = [NSString stringWithFormat:@"%02d:%02d:%02d",duration / 60 / 60, (duration / 60) % 60, duration % 60];
    cell.duration.text = [NSString stringWithFormat:@"%@",[self parseDuration:[[self.arrResult objectAtIndex:indexPath.row] valueForKey:@"duration"]]];
    cell.type.text = @"";
    
    if([[self.arrResult objectAtIndex:indexPath.row] valueForKey:@"thumbnailObject"]) {
        //UIImageView *imv = [[UIImageView alloc]initWithFrame:CGRectMake(3,2, cell.frame.size.height / 3 * 4, cell.frame.size.height)];
        cell.imv.backgroundColor = [UIColor clearColor];
        cell.imv.opaque = NO;
        cell.imv.image=[[self.arrResult objectAtIndex:indexPath.row] valueForKey:@"thumbnailObject"];
        //[cell.contentView addSubview:imv];
    }
    
    //cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
        return UITableViewAutomaticDimension;
        
    } else {
        NSString *cellIdentifier = [self reuseIdentifierForCellAtIndexPath:indexPath];
        static NSMutableDictionary *heightCache;
        if (!heightCache)
            heightCache = [[NSMutableDictionary alloc] init];
        NSNumber *cachedHeight = heightCache[cellIdentifier];
        if (cachedHeight)
            return cachedHeight.floatValue;
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        CGFloat height = cell.bounds.size.height;
        heightCache[cellIdentifier] = @(height);
        return height;
    }
}

- (NSString *)reuseIdentifierForCellAtIndexPath:(NSIndexPath *)indexPath {
    NSString * reuseIdentifier;
    /*
     switch (indexPath.row) {
     case 0:
     reuseIdentifier = EventTitleCellIdentifier;
     break;
     case 2:
     reuseIdentifier = EventDateTimeCellIdentifier;
     break;
     case 4:
     reuseIdentifier = EventContactsCellIdentifier;
     break;
     case 6:
     reuseIdentifier = EventLocationCellIdentifier;
     break;
     case 8:
     reuseIdentifier = NotesCellIdentifier;
     break;
     default:
     reuseIdentifier = SeparatorCellIdentifier;
     break;
     }
     */
    reuseIdentifier = @"searchResultTableCell";
    return reuseIdentifier;
}

- (NSArray *) preferredVideoQualities
{
    if (!_preferredVideoQualities)
        _preferredVideoQualities = @[ XCDYouTubeVideoQualityHTTPLiveStreaming, @(XCDYouTubeVideoQualityHD720), @(XCDYouTubeVideoQualityMedium360), @(XCDYouTubeVideoQualitySmall240) ];
    
    return _preferredVideoQualities;
}

- (void) stopWithError:(NSError *)error
{
}

- (void)saveVideoInfo:(NSString *)videoId
            videoItag:(NSString *)videoItag
        videoFilename:(NSString *)videoFilename{
    [[Operation sharedOperation] getVideoInfo:videoId
                                      success:^(id JSON) {
                                          NSLog(@"DONE!");
                                          
                                          if([JSON valueForKey:@"items"]) {
                                              NSDictionary * selectedKey = [JSON valueForKey:@"items"];
                                              
                                              for(id key in selectedKey) {
                                                  NSString * valueId = [key objectForKey:@"id"];
                                                  NSString * valueKind = [key objectForKey:@"kind"];
                                                  NSString * valueDescription = [[key objectForKey:@"snippet"] objectForKey:@"description"];
                                                  NSString * valuePublishedAt = [[key objectForKey:@"snippet"] objectForKey:@"publishedAt"];
                                                  
                                                  NSString * valueChannelId = [[key objectForKey:@"snippet"] objectForKey:@"channelId"];
                                                  NSString * valueChannelTitle = [[key objectForKey:@"snippet"] objectForKey:@"channelTitle"];
                                                  
                                                  NSString * valueDuration = [[key objectForKey:@"contentDetails"] objectForKey:@"duration"];
                                                  NSString * valueDefinition = [[key objectForKey:@"contentDetails"] objectForKey:@"definition"];
                                                  NSString * valueThumbnailUrl = [[[[key objectForKey:@"snippet"] objectForKey:@"thumbnails"] objectForKey:@"default"] objectForKey:@"url"];
                                                  NSString * valueTitle = [[key objectForKey:@"snippet"] objectForKey:@"title"];
                                                  NSString * valueDislikeCount = [[key objectForKey:@"statistics"] objectForKey:@"dislikeCount"];
                                                  NSString * valueLikeCount = [[key objectForKey:@"statistics"] objectForKey:@"likeCount"];
                                                  NSString * valueViewCount = [[key objectForKey:@"statistics"] objectForKey:@"viewCount"];
                                                  [[DBManager sharedInstance] saveVideoData:valueId videoFilename:videoFilename videoItag:videoItag videoTitle:valueTitle videoDescription:valueDescription videoDuration:valueDuration videoChannelId:valueChannelId videoChannelTitle:valueChannelTitle videoPublishedAt:valuePublishedAt raw:JSON];
                                                  
                                                  [[Operation sharedOperation] getRaw:valueThumbnailUrl
                                                                              success:^(id JSON) {
                                                                                  NSLog(@"get thumbnail DONE!");
                                                                                  
                                                                                  NSArray *filenameArray = [valueThumbnailUrl componentsSeparatedByString:@"/"];
                                                                                  NSString *filename = [filenameArray objectAtIndex:[filenameArray count] - 1];
                                                                                  
                                                                                  NSError *error;
                                                                                  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                                                                                  NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
                                                                                  NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/save"];
                                                                                  if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
                                                                                  {
                                                                                      [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
                                                                                  }
                                                                                  NSString *destinationPath = [dataPath stringByAppendingFormat:@"/%@_%@_%@", valueId,videoItag,filename];
                                                                                  bool writeResult = [JSON writeToFile:destinationPath atomically:true];
                                                                                  if(writeResult == YES) {
                                                                                      [[DBManager sharedInstance] saveVideoDataThumb:valueId videoFilename:[NSString stringWithFormat:@"%@_%@_%@", valueId,videoItag,filename]];
                                                                                      //[self showAlert:@"thumb アプリに保存" message:@"thumb 保存完了"];
                                                                                  }
                                                                              } failure:^(NSError *error, id JSON) {
                                                                                  NSLog(@"get thumbnail FAIL!");
                                                                              }];
                                              }
                                          }
                                          
                                      } failure:^(NSError *error, id JSON) {
                                          NSLog(@"FAIL!");
                                      }];
}

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if(self.selectionEnabled == 1) {
        return indexPath;
    } else {
        return nil;
    }
    
    // rows in section 0 should not be selectable
    if ( indexPath.section == 0 ) return nil;
    
    // first 3 rows in any section should not be selectable
    if ( indexPath.row <= 2 ) return nil;
    
    // By default, allow row to be selected
    return indexPath;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    // Get the record ID of the selected name and set it to the recordIDToEdit property.
    NSDictionary * selectedData = [self.arrResult objectAtIndex:indexPath.row];
    
    NSString *videoId = [selectedData valueForKey:@"id"];
    NSLog(@"%@",videoId);
    
    [self getVideoInfo:videoId];
    XCDYouTubeVideoPlayerViewController *videoPlayerViewController = [[XCDYouTubeVideoPlayerViewController alloc] initWithVideoIdentifier:videoId];
    videoPlayerViewController.moviePlayer.backgroundPlaybackEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:@"PlayVideoInBackground"];
    videoPlayerViewController.preferredVideoQualities = self.lowQualitySwitch.on ? @[ @(XCDYouTubeVideoQualitySmall240), @(XCDYouTubeVideoQualityMedium360) ] : nil;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerPlaybackDidFinish:) name:MPMoviePlayerPlaybackDidFinishNotification object:videoPlayerViewController.moviePlayer];
    videoPlayerViewController.moviePlayer.backgroundPlaybackEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:@"PlayVideoInBackground"];
    [self presentMoviePlayerViewControllerAnimated:videoPlayerViewController];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
}

- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @[
             [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal
                                                title:@"保存"
                                              handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
                                                  // own action
                                                  [tableView setEditing:NO animated:YES];
                                                  
                                                  
                                                  UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
                                                  [actionSheet addAction:[UIAlertAction actionWithTitle:@"キャンセル" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                                                      // Cancel button tappped do nothing.
                                                  }]];
                                                  [actionSheet addAction:[UIAlertAction actionWithTitle:@"大型の動画を保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                                                      // take photo button tapped.
                                                      NSLog(@"大型の動画を保存");
                                                      
                                                      // Get the record ID of the selected name and set it to the recordIDToEdit property.
                                                      NSDictionary * selectedData = [self.arrResult objectAtIndex:indexPath.row];
                                                      
                                                      NSString *videoId = [selectedData valueForKey:@"id"];
                                                      NSLog(@"%@",videoId);
                                                      
                                                      
                                                      self.selectionEnabled = 0;
                                                      self.preferredVideoQualities = @[ @(XCDYouTubeVideoQualityHD720)];
                                                      
                                                      NSString *videoIdentifier = videoId;
                                                      
                                                      [self.videoOperation cancel];
                                                      self.videoOperation = [[XCDYouTubeClient defaultClient] getVideoWithIdentifier:videoId completionHandler:^(XCDYouTubeVideo *video, NSError *error)
                                                                             {
                                                                                 if (video)
                                                                                 {
                                                                                     NSURL *streamURL = nil;
                                                                                     for (NSNumber *videoQuality in self.preferredVideoQualities)
                                                                                     {
                                                                                         streamURL = video.streamURLs[videoQuality];
                                                                                         if (streamURL)
                                                                                         {
                                                                                             [[Operation sharedOperation] streamToFile:[NSString stringWithFormat:@"%@", streamURL]
                                                                                                                            saveToPath:[NSString stringWithFormat:@"save/%@_%@.mp4",video.identifier,videoQuality]
                                                                                                                         progressBlock:^(double fractionCompleted) {
                                                                                                                             //NSLog(@"Progress: %f", fractionCompleted);
                                                                                                                             self.percentComplete.text = [NSString stringWithFormat:@"%.02f%%", fractionCompleted * 100];
                                                                                                                         }
                                                                                                                               success:^(NSString *savedTo) {
                                                                                                                                   NSLog(@"Saved to %@",savedTo);
                                                                                                                                   [self saveVideoInfo:video.identifier videoItag:[NSString stringWithFormat:@"%@",videoQuality] videoFilename:[NSString stringWithFormat:@"%@_%@.mp4",video.identifier,videoQuality]];
                                                                                                                                   //[self showAlert:@"アプリに保存" message:@"保存完了"];
                                                                                                                                   self.selectionEnabled = 1;
                                                                                                                                   self.percentComplete.text = @"完了";
                                                                                                                               }
                                                                                                                               failure:^(NSError *error) {
                                                                                                                                   //[self showAlert:@"アプリに保存" message:@"保存完了"];
                                                                                                                                   self.selectionEnabled = 1;
                                                                                                                                   self.percentComplete.text = @"失敗";
                                                                                                                               }];
                                                                                             break;
                                                                                         }
                                                                                     }
                                                                                     
                                                                                     if (!streamURL)
                                                                                     {
                                                                                         NSError *noStreamError = [NSError errorWithDomain:XCDYouTubeVideoErrorDomain code:XCDYouTubeErrorNoStreamAvailable userInfo:nil];
                                                                                         [self stopWithError:noStreamError];
                                                                                         self.selectionEnabled = 1;
                                                                                         [self showAlert:@"保存エラー" message:@"保存エラー"];
                                                                                     }
                                                                                 }
                                                                                 else
                                                                                 {
                                                                                     [self stopWithError:error];
                                                                                     self.selectionEnabled = 1;
                                                                                     [self showAlert:@"保存エラー" message:@"保存エラー"];
                                                                                 }
                                                                             }];
                                                  }]];
                                                  [actionSheet addAction:[UIAlertAction actionWithTitle:@"中型の動画を保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                                                      // take photo button tapped.
                                                      NSLog(@"中型の動画を保存");
                                                      
                                                      // Get the record ID of the selected name and set it to the recordIDToEdit property.
                                                      NSDictionary * selectedData = [self.arrResult objectAtIndex:indexPath.row];
                                                      
                                                      NSString *videoId = [selectedData valueForKey:@"id"];
                                                      NSLog(@"%@",videoId);
                                                      
                                                      
                                                      self.selectionEnabled = 0;
                                                      self.preferredVideoQualities = @[ @(XCDYouTubeVideoQualityMedium360)];
                                                      
                                                      NSString *videoIdentifier = videoId;
                                                      
                                                      [self.videoOperation cancel];
                                                      self.videoOperation = [[XCDYouTubeClient defaultClient] getVideoWithIdentifier:videoId completionHandler:^(XCDYouTubeVideo *video, NSError *error)
                                                                             {
                                                                                 if (video)
                                                                                 {
                                                                                     NSURL *streamURL = nil;
                                                                                     for (NSNumber *videoQuality in self.preferredVideoQualities)
                                                                                     {
                                                                                         streamURL = video.streamURLs[videoQuality];
                                                                                         if (streamURL)
                                                                                         {
                                                                                             [[Operation sharedOperation] streamToFile:[NSString stringWithFormat:@"%@", streamURL]
                                                                                                                            saveToPath:[NSString stringWithFormat:@"save/%@_%@.mp4",video.identifier,videoQuality]
                                                                                                                         progressBlock:^(double fractionCompleted) {
                                                                                                                             //NSLog(@"Progress: %f", fractionCompleted);
                                                                                                                             self.percentComplete.text = [NSString stringWithFormat:@"%.02f%%", fractionCompleted * 100];
                                                                                                                         }
                                                                                                                               success:^(NSString *savedTo) {
                                                                                                                                   NSLog(@"Saved to %@",savedTo);
                                                                                                                                   [self saveVideoInfo:video.identifier videoItag:[NSString stringWithFormat:@"%@",videoQuality] videoFilename:[NSString stringWithFormat:@"%@_%@.mp4",video.identifier,videoQuality]];
                                                                                                                                   //[self showAlert:@"アプリに保存" message:@"保存完了"];
                                                                                                                                   self.selectionEnabled = 1;
                                                                                                                                   self.percentComplete.text = @"完了";
                                                                                                                               }
                                                                                                                               failure:^(NSError *error) {
                                                                                                                                   //[self showAlert:@"アプリに保存" message:@"保存完了"];
                                                                                                                                   self.selectionEnabled = 1;
                                                                                                                                   self.percentComplete.text = @"失敗";
                                                                                                                               }];
                                                                                             break;
                                                                                         }
                                                                                     }
                                                                                     
                                                                                     if (!streamURL)
                                                                                     {
                                                                                         NSError *noStreamError = [NSError errorWithDomain:XCDYouTubeVideoErrorDomain code:XCDYouTubeErrorNoStreamAvailable userInfo:nil];
                                                                                         [self stopWithError:noStreamError];
                                                                                         self.selectionEnabled = 1;
                                                                                         [self showAlert:@"保存エラー" message:@"保存エラー"];
                                                                                     }
                                                                                 }
                                                                                 else
                                                                                 {
                                                                                     [self stopWithError:error];
                                                                                     self.selectionEnabled = 1;
                                                                                     [self showAlert:@"保存エラー" message:@"保存エラー"];
                                                                                 }
                                                                             }];
                                                  }]];
                                                  [actionSheet addAction:[UIAlertAction actionWithTitle:@"小型の動画を保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                                                      // take photo button tapped.
                                                      NSLog(@"小型の動画を保存");
                                                      
                                                      // Get the record ID of the selected name and set it to the recordIDToEdit property.
                                                      NSDictionary * selectedData = [self.arrResult objectAtIndex:indexPath.row];
                                                      
                                                      NSString *videoId = [selectedData valueForKey:@"id"];
                                                      NSLog(@"%@",videoId);
                                                      
                                                      
                                                      self.selectionEnabled = 0;
                                                      self.preferredVideoQualities = @[ @(XCDYouTubeVideoQualitySmall240)];
                                                      
                                                      NSString *videoIdentifier = videoId;
                                                      
                                                      [self.videoOperation cancel];
                                                      self.videoOperation = [[XCDYouTubeClient defaultClient] getVideoWithIdentifier:videoId completionHandler:^(XCDYouTubeVideo *video, NSError *error)
                                                                             {
                                                                                 if (video)
                                                                                 {
                                                                                     NSURL *streamURL = nil;
                                                                                     for (NSNumber *videoQuality in self.preferredVideoQualities)
                                                                                     {
                                                                                         streamURL = video.streamURLs[videoQuality];
                                                                                         if (streamURL)
                                                                                         {
                                                                                             [[Operation sharedOperation] streamToFile:[NSString stringWithFormat:@"%@", streamURL]
                                                                                                                            saveToPath:[NSString stringWithFormat:@"save/%@_%@.mp4",video.identifier,videoQuality]
                                                                                                                         progressBlock:^(double fractionCompleted) {
                                                                                                                             //NSLog(@"Progress: %f", fractionCompleted);
                                                                                                                             self.percentComplete.text = [NSString stringWithFormat:@"%.02f%%", fractionCompleted * 100];
                                                                                                                         }
                                                                                                                               success:^(NSString *savedTo) {
                                                                                                                                   NSLog(@"Saved to %@",savedTo);
                                                                                                                                   [self saveVideoInfo:video.identifier videoItag:[NSString stringWithFormat:@"%@",videoQuality] videoFilename:[NSString stringWithFormat:@"%@_%@.mp4",video.identifier,videoQuality]];
                                                                                                                                   //[self showAlert:@"アプリに保存" message:@"保存完了"];
                                                                                                                                   self.selectionEnabled = 1;
                                                                                                                                   self.percentComplete.text = @"完了";
                                                                                                                               }
                                                                                                                               failure:^(NSError *error) {
                                                                                                                                   //[self showAlert:@"アプリに保存" message:@"保存完了"];
                                                                                                                                   self.selectionEnabled = 1;
                                                                                                                                   self.percentComplete.text = @"失敗";
                                                                                                                               }];
                                                                                             break;
                                                                                         }
                                                                                     }
                                                                                     
                                                                                     if (!streamURL)
                                                                                     {
                                                                                         NSError *noStreamError = [NSError errorWithDomain:XCDYouTubeVideoErrorDomain code:XCDYouTubeErrorNoStreamAvailable userInfo:nil];
                                                                                         [self stopWithError:noStreamError];
                                                                                         self.selectionEnabled = 1;
                                                                                         [self showAlert:@"保存エラー" message:@"保存エラー"];
                                                                                     }
                                                                                 }
                                                                                 else
                                                                                 {
                                                                                     [self stopWithError:error];
                                                                                     self.selectionEnabled = 1;
                                                                                     [self showAlert:@"保存エラー" message:@"保存エラー"];
                                                                                 }
                                                                             }];
                                                  }]];
                                                  [self presentViewController:actionSheet animated:YES completion:nil];
                                              }],
             ];
}

- (IBAction) endEditing:(id)sender
{
    [self.view endEditing:YES];
}

#pragma mark - Notifications

- (void) moviePlayerPlaybackDidFinish:(NSNotification *)notification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:notification.object];
    MPMovieFinishReason finishReason = [notification.userInfo[MPMoviePlayerPlaybackDidFinishReasonUserInfoKey] integerValue];
    if (finishReason == MPMovieFinishReasonPlaybackError)
    {
        NSString *title = NSLocalizedString(@"Video Playback Error", @"Full screen video error alert - title");
        NSError *error = notification.userInfo[XCDMoviePlayerPlaybackDidFinishErrorUserInfoKey];
        NSString *message = [NSString stringWithFormat:@"%@\n%@ (%@)", error.localizedDescription, error.domain, @(error.code)];
        NSString *cancelButtonTitle = NSLocalizedString(@"OK", @"Full screen video error alert - cancel button");
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:cancelButtonTitle otherButtonTitles:nil];
        [alertView show];
    }
}

- (void)showAlert:(NSString*)title message:(NSString*)message{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                    message:message
                                                   delegate:self
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    [_mask removeFromSuperview];
}

- (NSString *)parseDuration:(NSString *)duration {
    NSInteger hours = 0;
    NSInteger minutes = 0;
    NSInteger seconds = 0;
    
    NSRange timeRange = [duration rangeOfString:@"T"];
    duration = [duration substringFromIndex:timeRange.location];
    
    while (duration.length > 1) {
        duration = [duration substringFromIndex:1];
        
        NSScanner *scanner = [NSScanner.alloc initWithString:duration];
        NSString *part = [NSString.alloc init];
        [scanner scanCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet] intoString:&part];
        
        NSRange partRange = [duration rangeOfString:part];
        
        duration = [duration substringFromIndex:partRange.location + partRange.length];
        
        NSString *timeUnit = [duration substringToIndex:1];
        if ([timeUnit isEqualToString:@"H"])
            hours = [part integerValue];
        else if ([timeUnit isEqualToString:@"M"])
            minutes = [part integerValue];
        else if ([timeUnit isEqualToString:@"S"])
            seconds = [part integerValue];
    }
    
    return [NSString stringWithFormat:@"%02ld:%02ld:%02ld", (long)hours, (long)minutes, (long)seconds];
}

@end
