//
//  SecondViewController.m
//  tuber
//
//  Created by ドラッサル 亜嵐 on 2016/06/09.
//  Copyright © 2016年 ドラッサル 亜嵐. 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 "SecondViewController.h"
#import "Operation.h"
#import "DBManager.h"
#import "OperationDropbox.h"

#import "XCDYouTubeKit/XCDYouTubeKit.h"

#import "MPMoviePlayerController+BackgroundPlayback.h"

#import "searchResultTableCell.h"

#import <Photos/Photos.h>

#import <AVFoundation/AVAsset.h>

@interface SecondViewController () {
    UIView *_mask;
}

@property (nonatomic, strong) NSMutableArray *arrResult;
@property (nonatomic, strong) DBManager *dbManager;
@property (nonatomic, strong) AVAssetExportSession *exportSession;

@end

@implementation SecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleDidLinkNotification:) name:@"didLinkToDropboxAccountNotification" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleDidUnlinkNotification:) name:@"didUnlinkFromDropboxAccountNotification" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleDidFinishUploadNotification:) name:@"didFinishFromDropboxUploadNotification" object:nil];
    
    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];
    
    [OperationDropbox sharedInstance].rootViewController = self;
    if([[OperationDropbox sharedInstance] isLinked]) {
        btnDropboxAuth.title = @"ログアウト";
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [self populateDetail];
}

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

- (void)populateDetail {
    [self.arrResult removeAllObjects];

    NSArray *result = [[DBManager sharedInstance] getVideoDataList];
    
    for(id key in result) {
        NSString *valueId = [key objectAtIndex:0];
        NSString *valueVideoId = [key objectAtIndex:1];
        NSString *valueFilename = [key objectAtIndex:2];
        NSString *valueItag = [key objectAtIndex:3];
        NSString *valueDuration = [key objectAtIndex:6];
        
        NSString *valueChannelId = [key objectAtIndex:7];
        NSString *valueChannelTitle = [key objectAtIndex:8];
        
        NSString *valueThumbnail = [key objectAtIndex:9];
        NSString *valueTitle = [key objectAtIndex:4];
        NSString *valueDescription = [key objectAtIndex:5];
        
        
        NSMutableDictionary *newDict = [NSMutableDictionary dictionary];
        [newDict setObject:valueId forKey:@"id"];
        [newDict setObject:valueVideoId forKey:@"videoid"];
        [newDict setObject:valueFilename forKey:@"filename"];
        [newDict setObject:valueItag forKey:@"itag"];
        [newDict setObject:valueDuration forKey:@"duration"];
        [newDict setObject:valueThumbnail forKey:@"thumbnail"];
        [newDict setObject:valueTitle forKey:@"title"];
        [newDict setObject:valueDescription forKey:@"description"];
        
        [newDict setObject:valueChannelId forKey:@"channelId"];
        [newDict setObject:valueChannelTitle forKey:@"channelTitle"];
        

        [self insertImage:[[Operation sharedOperation] getImageFromFile:valueThumbnail] dictionary:newDict];
        
        /*
         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:(UIImage *)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"]]];
    if([[[self.arrResult objectAtIndex:indexPath.row] valueForKey:@"itag"] integerValue] == XCDYouTubeVideoQualitySmall240) {
        cell.type.text = @"小型";
    } else if([[[self.arrResult objectAtIndex:indexPath.row] valueForKey:@"itag"] integerValue] == XCDYouTubeVideoQualityMedium360) {
        cell.type.text = @"中型";
    } else if([[[self.arrResult objectAtIndex:indexPath.row] valueForKey:@"itag"] integerValue] == XCDYouTubeVideoQualityHD720) {
        cell.type.text = @"大型";
    } else {
        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;
}

- (void)infoBtnClicked:(id)sender {
    UIButton *clicked = (UIButton *) sender;
    NSLog(@"Clicked item at index %ld",clicked.tag);
    
    NSInteger index = clicked.tag;
    
    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:index];
        
        NSString *videoFilename = [selectedData valueForKey:@"filename"];
        NSLog(@"videoFilename = %@",videoFilename);
        
        
        NSString *docPath = [NSSearchPathForDirectoriesInDomains
                             (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString *docPathFull = [docPath stringByAppendingPathComponent:[NSString stringWithFormat:@"/save/%@",videoFilename]];
        NSURL *docPathFullUrl = [NSURL URLWithString:docPathFull];
        
        // After that use this path to save it to PhotoLibrary
        PHAssetCollection *assetAlbum = [self getAPPCollection];


        
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            // Request creating an asset from the image.
            PHAssetChangeRequest *createAssetRequest = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:docPathFullUrl];
            // Request editing the album.
            PHAssetCollectionChangeRequest *albumChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetAlbum];
            // Get a placeholder for the new asset and add it to the album editing request.
            PHObjectPlaceholder *assetPlaceholder = [createAssetRequest placeholderForCreatedAsset];
            [albumChangeRequest addAssets:@[ assetPlaceholder ]];
        } completionHandler:^(BOOL success, NSError *error) {
            if (success) {
                /*
                 NSString *UUID = [placeholder.localIdentifier substringToIndex:36];
                 self.photo.assetURL = [NSString stringWithFormat:@"assets-library://asset/asset.PNG?id=%@&ext=JPG", UUID];
                 [self savePhoto];
                 */
                NSLog(@"Success");
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self showAlert:@"写真に追加" message:@"保存しました"];
                });
            } else {
                NSLog(@"Error");
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self showAlert:@"写真に追加" message:@"失敗しました"];
                });
            }
        }];
    }]];
    [actionSheet addAction:[UIAlertAction actionWithTitle:@"削除" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
        // take photo button tapped.
        NSLog(@"削除");
        
        
        NSDictionary * selectedData = [self.arrResult objectAtIndex:index];
        NSString *videoTitle = [selectedData valueForKey:@"title"];
        
        UIAlertController *actionSheetConfirm = [UIAlertController alertControllerWithTitle:@"削除の確認" message:[NSString stringWithFormat:@"「%@」を削除します。よろしいですか？",videoTitle] preferredStyle:UIAlertControllerStyleAlert];
        
        [actionSheetConfirm addAction:[UIAlertAction actionWithTitle:@"削除" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *actionConfirm) {
            // Distructive button tapped.
            NSLog(@"削除の確認");
            
            // Get the record ID of the selected name and set it to the recordIDToEdit property.
            NSDictionary * selectedData = [self.arrResult objectAtIndex:index];
            
            NSString *videoId = [selectedData valueForKey:@"id"];
            NSLog(@"videoId = %@",videoId);
            NSString *videoFilename = [selectedData valueForKey:@"filename"];
            NSLog(@"videoFilename = %@",videoFilename);
            
            
            NSString *docPath = [NSSearchPathForDirectoriesInDomains
                                 (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            NSString *docPathFull = [docPath stringByAppendingPathComponent:[NSString stringWithFormat:@"/save/%@",videoFilename]];
            //NSURL *docPathFullUrl = [NSURL URLWithString:docPathFull];

            
            NSFileManager *fileManager = [NSFileManager defaultManager];
            NSError *error;
            BOOL success = [fileManager removeItemAtPath:docPathFull error:&error];
            if(success) {
                NSLog(@"削除した");
                [[DBManager sharedInstance] deleteVideoData:videoId];
                [self populateDetail];
                [self.tblResult reloadData];
            } else {
                NSLog(@"削除を失敗した");
                [[DBManager sharedInstance] deleteVideoData:videoId];
                [self populateDetail];
                [self.tblResult reloadData];
            }
        }]];
        [actionSheetConfirm addAction:[UIAlertAction actionWithTitle:@"キャンセル" style:UIAlertActionStyleDefault handler:^(UIAlertAction *actionConfirm) {
            // Distructive button tapped.
            NSLog(@"キャンセルの確認");
        }]];
        [self presentViewController:actionSheetConfirm animated:YES completion:nil];
    }]];
    /*
    [actionSheet addAction:[UIAlertAction actionWithTitle:@"ミュージックに追加" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        // choose photo button tapped.
        NSLog(@"ミュージックに追加");
        
        // Get the record ID of the selected name and set it to the recordIDToEdit property.
        NSDictionary * selectedData = [self.arrResult objectAtIndex:index];
        
        NSString *videoFilename = [selectedData valueForKey:@"filename"];
        NSLog(@"%@",videoFilename);
        
        
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        NSString *videoPath = [NSString stringWithFormat:@"save/%@",videoFilename];
        NSURL *videoPathFullUrl = [documentsDirectoryURL URLByAppendingPathComponent:videoPath];

        
        NSString *audioId = [NSString stringWithFormat:@"%@%@",videoFilename,@".m4a"];
        NSString *audioPath = [NSString stringWithFormat:@"save/%@",audioId];
        NSURL *audioPathFullUrl = [documentsDirectoryURL URLByAppendingPathComponent:audioPath];

        
        [self convertVideoToAudioWithInputURL:(NSURL*)videoPathFullUrl
                                    outputURL:(NSURL*)audioPathFullUrl
                                      handler:^(AVAssetExportSession *handler) {
                                          NSLog(@"convert to m4a complete");
                                          [self showAlert:@"ミュージックに追加" message:@"保存しました"];
        }];
    }]];
     */
    /*
    [actionSheet addAction:[UIAlertAction actionWithTitle:@"Delete Photo" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
        // Distructive button tapped.
        NSLog(@"delete photo");
    }]];
     */
    [self presentViewController:actionSheet animated:YES completion:nil];
}

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

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

- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @[
             [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive
                                                title:@"削除"
                                              handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
                                                  // own delete action

                                                  
                                                  // Distructive button tapped.
                                                  NSLog(@"削除の確認");
                                                  
                                                  NSDictionary * selectedData = [self.arrResult objectAtIndex:indexPath.row];
                                                  NSString *videoTitle = [selectedData valueForKey:@"title"];

                                                  UIAlertController *actionSheetConfirm = [UIAlertController alertControllerWithTitle:@"削除の確認" message:[NSString stringWithFormat:@"「%@」を削除します。よろしいですか？",videoTitle] preferredStyle:UIAlertControllerStyleAlert];
                                                  
                                                  [actionSheetConfirm addAction:[UIAlertAction actionWithTitle:@"削除" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *actionConfirm) {
                                                      
                                                      
                                                      // Get the record ID of the selected name and set it to the recordIDToEdit property.
                                                      NSDictionary * selectedData = [self.arrResult objectAtIndex:indexPath.row];
                                                      
                                                      NSString *recordId = [selectedData valueForKey:@"id"];
                                                      NSLog(@"recordId = %@",recordId);
                                                      NSString *videoFilename = [selectedData valueForKey:@"filename"];
                                                      NSLog(@"videoFilename = %@",videoFilename);
                                                      
                                                      
                                                      NSString *docPath = [NSSearchPathForDirectoriesInDomains
                                                                           (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                                                      NSString *docPathFull = [docPath stringByAppendingPathComponent:[NSString stringWithFormat:@"/save/%@",videoFilename]];
                                                      //NSURL *docPathFullUrl = [NSURL URLWithString:docPathFull];
                                                      
                                                      
                                                      NSFileManager *fileManager = [NSFileManager defaultManager];
                                                      NSError *error;
                                                      BOOL success = [fileManager removeItemAtPath:docPathFull error:&error];
                                                      if(success) {
                                                          NSLog(@"削除した");
                                                          [[DBManager sharedInstance] deleteVideoData:recordId];
                                                          //[self populateDetail];
                                                          //[self.tblResult reloadData];
                                                          [self.arrResult removeObjectAtIndex:indexPath.row];
                                                          [self.tblResult deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
                                                      } else {
                                                          NSLog(@"削除を失敗した");
                                                          [[DBManager sharedInstance] deleteVideoData:recordId];
                                                          //[self populateDetail];
                                                          //[self.tblResult reloadData];
                                                          [self.arrResult removeObjectAtIndex:indexPath.row];
                                                          [self.tblResult deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
                                                      }
                                                  }]];
                                                  [actionSheetConfirm addAction:[UIAlertAction actionWithTitle:@"キャンセル" style:UIAlertActionStyleDefault handler:^(UIAlertAction *actionConfirm) {
                                                      // Distructive button tapped.
                                                      NSLog(@"キャンセルの確認");
                                                  }]];
                                                  [self presentViewController:actionSheetConfirm animated:YES completion:nil];
                                              }],
             [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal
                                                title:@"コピー"
                                              handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
                                                  // own action
                                                  [tableView setEditing:NO animated:YES];

                                                  NSLog(@"コピー");

                                                  
                                                  
                                                  
                                                  
                                                  
                                                  
                                                  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 *videoFilename = [selectedData valueForKey:@"filename"];
                                                      NSLog(@"videoFilename = %@",videoFilename);
                                                      
                                                      
                                                      NSString *docPath = [NSSearchPathForDirectoriesInDomains
                                                                           (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                                                      NSString *docPathFull = [docPath stringByAppendingPathComponent:[NSString stringWithFormat:@"/save/%@",videoFilename]];
                                                      NSURL *docPathFullUrl = [NSURL URLWithString:docPathFull];
                                                      
                                                      // After that use this path to save it to PhotoLibrary
                                                      PHAssetCollection *assetAlbum = [self getAPPCollection];
                                                      
                                                      
                                                      
                                                      [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                                                          // Request creating an asset from the image.
                                                          PHAssetChangeRequest *createAssetRequest = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:docPathFullUrl];
                                                          // Request editing the album.
                                                          PHAssetCollectionChangeRequest *albumChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetAlbum];
                                                          // Get a placeholder for the new asset and add it to the album editing request.
                                                          PHObjectPlaceholder *assetPlaceholder = [createAssetRequest placeholderForCreatedAsset];
                                                          [albumChangeRequest addAssets:@[ assetPlaceholder ]];
                                                      } completionHandler:^(BOOL success, NSError *error) {
                                                          if (success) {
                                                              /*
                                                               NSString *UUID = [placeholder.localIdentifier substringToIndex:36];
                                                               self.photo.assetURL = [NSString stringWithFormat:@"assets-library://asset/asset.PNG?id=%@&ext=JPG", UUID];
                                                               [self savePhoto];
                                                               */
                                                              NSLog(@"Success");
                                                              dispatch_async(dispatch_get_main_queue(), ^{
                                                                  [self showAlert:@"写真に追加" message:@"保存しました"];
                                                              });
                                                          } else {
                                                              NSLog(@"Error");
                                                              dispatch_async(dispatch_get_main_queue(), ^{
                                                                  [self showAlert:@"写真に追加" message:@"失敗しました"];
                                                              });
                                                          }
                                                      }];
                                                  }]];

                                                  [actionSheet addAction:[UIAlertAction actionWithTitle:@"Dropboxにアップロード（音楽）" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                                                      // choose photo button tapped.
                                                      NSLog(@"Dropboxにアップロード（音楽）");
                                                      
                                                      // Get the record ID of the selected name and set it to the recordIDToEdit property.
                                                      NSDictionary * selectedData = [self.arrResult objectAtIndex:indexPath.row];
                                                      
                                                      NSString *videoFilename = [selectedData valueForKey:@"filename"];
                                                      NSLog(@"%@",videoFilename);
                                                      
                                                      
                                                      NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
                                                      NSString *videoPath = [NSString stringWithFormat:@"save/%@",videoFilename];
                                                      NSURL *videoPathFullUrl = [documentsDirectoryURL URLByAppendingPathComponent:videoPath];
                                                      
                                                      
                                                      NSString *audioId = [NSString stringWithFormat:@"%@%@",[videoFilename stringByDeletingPathExtension],@"_audio.m4a"];
                                                      NSString *audioPath = [NSString stringWithFormat:@"save/%@",audioId];
                                                      NSURL *audioPathFullUrl = [documentsDirectoryURL URLByAppendingPathComponent:audioPath];
                                                      
                                                      NSString *localDir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
                                                      NSString *localPath = [localDir stringByAppendingPathComponent:audioPath];
                                                      
                                                      NSString *uploadFileName = [[NSString stringWithFormat:@"%@.m4a",[selectedData valueForKey:@"title"]] stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
                                                      
                                                      [self convertVideoToAudioWithInputURL:(NSURL*)videoPathFullUrl
                                                                                  outputURL:(NSURL*)audioPathFullUrl
                                                                                    handler:^(AVAssetExportSession *handler) {
                                                                                        NSLog(@"convert to m4a complete");
                                                                                        dispatch_async(dispatch_get_main_queue(), ^{
                                                                                            //[self showAlert:@"ミュージックに追加" message:@"保存しました"];
                                                                                            [[OperationDropbox sharedInstance] uploadFile:uploadFileName
                                                                                                                               sourcePath:localPath
                                                                                                                                  success:^(id JSON) {
                                                                                                                                      NSLog(@"Dropbox SUCCESS");
                                                                                                                                  }
                                                                                                                                  failure:^(NSError *error, id JSON) {
                                                                                                                                      NSLog(@"Dropbox RROR");
                                                                                                                                  }];
                                                                                        });
                                                                                    }];
                                                  }]];
                                                  [self presentViewController:actionSheet animated:YES completion:nil];

                                                  
                                                  
                                                  
                                                  
                                                  
                                                  
                                                  
                                                  
                                                  
                                                  /*
                                                  // Get the record ID of the selected name and set it to the recordIDToEdit property.
                                                  NSDictionary * selectedData = [self.arrResult objectAtIndex:indexPath.row];
                                                  
                                                  NSString *videoFilename = [selectedData valueForKey:@"filename"];
                                                  NSLog(@"%@",videoFilename);
                                                  
                                                  
                                                  NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
                                                  NSString *videoPath = [NSString stringWithFormat:@"save/%@",videoFilename];
                                                  NSURL *videoPathFullUrl = [documentsDirectoryURL URLByAppendingPathComponent:videoPath];
                                                  
                                                  
                                                  NSString *audioId = [NSString stringWithFormat:@"%@%@",[videoFilename stringByDeletingPathExtension],@"_audio.m4a"];
                                                  NSString *audioPath = [NSString stringWithFormat:@"save/%@",audioId];
                                                  NSURL *audioPathFullUrl = [documentsDirectoryURL URLByAppendingPathComponent:audioPath];

                                                  NSString *localDir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
                                                  NSString *localPath = [localDir stringByAppendingPathComponent:audioPath];
                                                  
                                                  NSString *uploadFileName = [[NSString stringWithFormat:@"%@.m4a",[selectedData valueForKey:@"title"]] stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
                                                  
                                                  [self convertVideoToAudioWithInputURL:(NSURL*)videoPathFullUrl
                                                                              outputURL:(NSURL*)audioPathFullUrl
                                                                                handler:^(AVAssetExportSession *handler) {
                                                                                    NSLog(@"convert to m4a complete");
                                                                                    dispatch_async(dispatch_get_main_queue(), ^{
                                                                                        //[self showAlert:@"ミュージックに追加" message:@"保存しました"];
                                                                                        [[OperationDropbox sharedInstance] uploadFile:uploadFileName
                                                                                                                           sourcePath:localPath
                                                                                                                              success:^(id JSON) {
                                                                                                                                  NSLog(@"Dropbox SUCCESS");
                                                                                                                              }
                                                                                                                              failure:^(NSError *error, id JSON) {
                                                                                                                                  NSLog(@"Dropbox RROR");
                                                                                                                              }];
                                                                                    });
                                                                                }];
                                                   */
                                              }],
             ];
}

-(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 *videoFilename = [selectedData valueForKey:@"filename"];
    NSLog(@"%@",videoFilename);
    
    
    NSString *docPath = [NSSearchPathForDirectoriesInDomains
                         (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *docaPathFull = [docPath stringByAppendingPathComponent:[NSString stringWithFormat:@"/save/%@",videoFilename]];
    NSURL *docUrl= [NSURL fileURLWithPath:docaPathFull];
    BOOL ex = [[NSFileManager defaultManager] fileExistsAtPath:docaPathFull];
    NSLog(@"file exists: %d, path using docPath: %@",ex, docaPathFull);
    MPMoviePlayerViewController *player = [[MPMoviePlayerViewController alloc] initWithContentURL:docUrl];
    [player.view setFrame: self.view.bounds];
    [player.moviePlayer prepareToPlay];
    [self.view addSubview:player.view];
    //player.moviePlayer.controlStyle = MPMovieControlStyleDefault;
    player.moviePlayer.controlStyle = MPMovieControlStyleFullscreen;
    player.moviePlayer.shouldAutoplay = YES;
    //[player.moviePlayer setFullscreen:YES animated:YES];
    [player.moviePlayer play];
    player.moviePlayer.backgroundPlaybackEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:@"PlayVideoInBackground"];
    [self presentMoviePlayerViewControllerAnimated: player];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return 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];
}

    //写真設定：参照（アプリの設定で許可されているかどうか）
-(BOOL)isPermitPhotoLibrary {
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    switch (status) {
        case PHAuthorizationStatusNotDetermined:
        // このアプリに与える権限が未選択（アプリ初回起動時）
        return NO;
        break;
        
        case PHAuthorizationStatusRestricted:
        // 設定による使用制限で、アプリのアクセスの許可を変更できない
        return NO;
        break;
        
        case PHAuthorizationStatusDenied:
        // このアプリに与える権限を拒否（アプリ初回起動時「許可しない」を選択）
        return NO;
        break;
        
        default:
        case PHAuthorizationStatusAuthorized:
        // このアプリに与える権限を許可（アプリ初回起動時「OK」を選択）
        return YES;
        break;
    }
}

//获取自定义相册
- (PHAssetCollection *)getAPPCollection {
    // Getting the app album if any: 找是否已经创建自定义相册
    PHFetchResult<PHAssetCollection *> *collectionResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    if([collectionResult count] == 0) {
        return nil;
    }
    NSString *appName = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleNameKey];
    for (PHAssetCollection *collection in collectionResult) {
        if ([collection.localizedTitle isEqualToString:appName]) {
            return collection;
        }
    }
    
    // Creating the album: 新建自定义相册
    __block NSString *collectionId = nil;
    NSError *error = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        collectionId = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:appName].placeholderForCreatedAssetCollection.localIdentifier;
    } error:&error];
    if (error) {
        NSLog(@"创建相册：%@失败", appName);
        return nil;
    }
    return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[collectionId] options:nil].lastObject;
}

- (void)convertVideoToAudioWithInputURL:(NSURL*)inputURL
                              outputURL:(NSURL*)outputURL
                                handler:(void (^)(AVAssetExportSession*))handler {
    AVURLAsset* asset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
    self.exportSession = [[AVAssetExportSession alloc] initWithAsset:asset
                                                          presetName: AVAssetExportPresetPassthrough];
    self.exportSession.outputURL = outputURL;
    self.exportSession.outputFileType = AVFileTypeAppleM4A; //For audio file
    self.exportSession.timeRange = CMTimeRangeMake(kCMTimeZero, [asset duration]);
    [self.exportSession exportAsynchronouslyWithCompletionHandler:^(void) {
        handler(self.exportSession);
    }];
}
    
- (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];
}

- (IBAction) connectToDropbox:(id)sender {
    [[OperationDropbox sharedInstance] connectToDropbox:self];
}

- (void)handleDidLinkNotification:(NSNotification *)notification {
    btnDropboxAuth.title = @"ログアウト";
}

- (void)handleDidUnlinkNotification:(NSNotification *)notification {
    btnDropboxAuth.title = @"ログイン";
}

- (void)handleDidFinishUploadNotification:(NSNotification *)notification {
    NSMutableDictionary *uploadStatus = (NSMutableDictionary*)notification.object;
    
    NSString *srcPath = [uploadStatus valueForKey:@"srcPath"];
    NSString *destPath = [uploadStatus valueForKey:@"destPath"];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    BOOL success = [fileManager removeItemAtPath:srcPath error:&error];
    if(success) {
        NSLog(@"%@ 削除した", srcPath);
    } else {
        NSLog(@"%@ 削除を失敗した", srcPath);
    }
    
    [self showAlert:@"Dropboxアップロード" message:[NSString stringWithFormat:@"%@\n\nをアップロードしました！",destPath]];
}

@end
