<commit_before>/**
 Copyright (c) 2016 <NAME>
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
 http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 **/

import AVFoundation
import CoreData
import Foundation
import Photos

class VideoManager {
    
    lazy var managedContext: NSManagedObjectContext? = {
        if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
            return appDelegate.managedObjectContext
        }
        
        return nil
    }()
    
    func getVideos() -> [Video] {
        var videos = [Video]()
        
        let fetchRequest = NSFetchRequest(entityName: "Video")
        fetchRequest.sortDescriptors = [NSSortDescriptor(key: "openDate", ascending: false)]
        
        do {
            let results = try managedContext?.executeFetchRequest(fetchRequest)
            if let objects = results as? [NSManagedObject] {
                for object in objects {
                    videos.append(Video(fromObject: object))
                }
            }
        } catch _ {
            
        }
        
        return videos
    }
    
    func getVideoByAssetId(assetId: String) -> Video? {
        let fetchRequest = NSFetchRequest(entityName: "Video")
        fetchRequest.predicate = NSPredicate(format: "assetId == %@", assetId)
        
        do {
            let results = try managedContext?.executeFetchRequest(fetchRequest)
            if let objects = results as? [NSManagedObject] {
                if objects.count == 1 {
                    return Video(fromObject: objects[0])
                }
            }
        } catch _ {
            
        }
        
        return nil
    }
    
    func updateOpenDate(video: Video) {
        video.coreDataObject.setValue(NSDate(), forKey: "openDate")
        
        do {
            try managedContext?.save()
        } catch _ {
            
        }
    }
    
    typealias CompletionHandler = (result:Video?) -> Void
    
    func addVideoFromAVURLAsset(asset: AVURLAsset, phAsset: PHAsset, completionHandler: CompletionHandler) {
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
            let filemgr = NSFileManager.defaultManager()
            let lastPathComponent = asset.URL.lastPathComponent
            let videoName = lastPathComponent != nil ? lastPathComponent! :"video_\(NSDate().timeIntervalSince1970).MOV"
            
            let videoURL = self.getDocumentUrl(videoName)
            let creationDate = phAsset.creationDate
            let assetId = phAsset.localIdentifier
            
            do {
                try filemgr.copyItemAtURL(asset.URL, toURL: videoURL)
            } catch _ {
                print("Failed to copy")
                completionHandler(result: nil)
            }
            
            let thumbURL = self.getDocumentUrl("\(videoName).png")
            
            let thumbSize: CGSize = CGSizeMake(CGFloat(phAsset.pixelWidth), CGFloat(phAsset.pixelHeight))
            
            let options = PHImageRequestOptions()
            options.synchronous = true
            
            let cachingImageManager = PHCachingImageManager()
            cachingImageManager.requestImageForAsset(phAsset, targetSize: thumbSize, contentMode: PHImageContentMode.AspectFill, options: options, resultHandler: { (image: UIImage?, info :[NSObject : AnyObject]?) -> Void in
                if let image = image {
                    UIImagePNGRepresentation(image)?.writeToURL(thumbURL, atomically: true)
                }
            })
            
            let video = self.addVideo(assetId, videoURL: videoURL, thumbURL: thumbURL, creationDate: creationDate)
            completionHandler(result: video)
        }
    }
    
    func addVideoFromURL(url: NSURL, completionHandler: CompletionHandler) {
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
            let filemgr = NSFileManager.defaultManager()
            let lastPathComponent = url.lastPathComponent
            let videoName = lastPathComponent != nil ? lastPathComponent! :"video_\(NSDate().timeIntervalSince1970).MOV"
            
            let videoURL = self.getDocumentUrl(videoName)
            let creationDate = NSDate()
            let assetId = ""
            
            do {
                try filemgr.copyItemAtURL(url, toURL: videoURL)
            } catch _ {
                print("Failed to copy")
                completionHandler(result: nil)
            }
            
            let thumbURL = self.getDocumentUrl("\(videoName).png")
            
            let duration = MediaUtils.getVideoDuration(videoURL)
            let thumbTime = CMTime(seconds: duration.seconds / 2.0, preferredTimescale: duration.timescale)
            <commit_msg>If we fail to get image from PHCachingImageManager.requestImageForAsset, use location thumbnail generation code<commit_after>/**
 Copyright (c) 2016 <NAME>
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
 http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 **/

import AVFoundation
import CoreData
import Foundation
import Photos

class VideoManager {
    
    lazy var managedContext: NSManagedObjectContext? = {
        if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
            return appDelegate.managedObjectContext
        }
        
        return nil
    }()
    
    func getVideos() -> [Video] {
        var videos = [Video]()
        
        let fetchRequest = NSFetchRequest(entityName: "Video")
        fetchRequest.sortDescriptors = [NSSortDescriptor(key: "openDate", ascending: false)]
        
        do {
            let results = try managedContext?.executeFetchRequest(fetchRequest)
            if let objects = results as? [NSManagedObject] {
                for object in objects {
                    videos.append(Video(fromObject: object))
                }
            }
        } catch _ {
            
        }
        
        return videos
    }
    
    func getVideoByAssetId(assetId: String) -> Video? {
        let fetchRequest = NSFetchRequest(entityName: "Video")
        fetchRequest.predicate = NSPredicate(format: "assetId == %@", assetId)
        
        do {
            let results = try managedContext?.executeFetchRequest(fetchRequest)
            if let objects = results as? [NSManagedObject] {
                if objects.count == 1 {
                    return Video(fromObject: objects[0])
                }
            }
        } catch _ {
            
        }
        
        return nil
    }
    
    func updateOpenDate(video: Video) {
        video.coreDataObject.setValue(NSDate(), forKey: "openDate")
        
        do {
            try managedContext?.save()
        } catch _ {
            
        }
    }
    
    typealias CompletionHandler = (result:Video?) -> Void
    
    func addVideoFromAVURLAsset(asset: AVURLAsset, phAsset: PHAsset, completionHandler: CompletionHandler) {
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
            let filemgr = NSFileManager.defaultManager()
            let lastPathComponent = asset.URL.lastPathComponent
            let videoName = lastPathComponent != nil ? lastPathComponent! :"video_\(NSDate().timeIntervalSince1970).MOV"
            
            let videoURL = self.getDocumentUrl(videoName)
            let creationDate = phAsset.creationDate
            let assetId = phAsset.localIdentifier
            
            do {
                try filemgr.copyItemAtURL(asset.URL, toURL: videoURL)
            } catch _ {
                print("Failed to copy")
                completionHandler(result: nil)
            }
            
            let thumbURL = self.getDocumentUrl("\(videoName).png")
            
            let thumbSize: CGSize = CGSizeMake(CGFloat(phAsset.pixelWidth), CGFloat(phAsset.pixelHeight))
            
            let options = PHImageRequestOptions()
            options.synchronous = true
            
            let cachingImageManager = PHCachingImageManager()
            cachingImageManager.requestImageForAsset(phAsset, targetSize: thumbSize, contentMode: PHImageContentMode.AspectFill, options: options, resultHandler: { (image: UIImage?, info :[NSObject : AnyObject]?) -> Void in
                if let image = image {
                    UIImagePNGRepresentation(image)?.writeToURL(thumbURL, atomically: true)
                } else {
                    let duration = MediaUtils.getVideoDuration(videoURL)
                    let thumbTime = CMTime(seconds: duration.seconds / 2.0, preferredTimescale: duration.timescale)
                    
                    MediaUtils.renderThumbnailFromVideo(videoURL, thumbURL: thumbURL, time: thumbTime)
                    
                }
            })
            
            let video = self.addVideo(assetId, videoURL: videoURL, thumbURL: thumbURL, creationDate: creationDate)
            completionHandler(result: video)
        }
    }
    
    func addVideoFromURL(url: NSURL, completionHandler: CompletionHandler) {
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
            let filemgr = NSFileManager.defaultManager()
            let lastPathComponent = url.lastPathComponent
            let videoName = lastPathComponent != nil ? lastPathComponent! :"video_\(NSDate().timeIntervalSince1970).MOV"
            
            let videoURL = self.getDocumentUrl(videoName)
            let creationDate = NSDate()
            let assetId = ""
            
            do {
                try filemgr.copyItemAtURL(url, toURL: videoURL)
            } catch _ {
                print("Failed to copy")
                completionHandler(result: nil)
            }
            
            let thumbURL = self.getDocumentUrl("\(videoName).png")
            
            let duration = MediaUtils.getVideoDuration(videoURL)
            let thumbTime = CMTime(seconds: duration.seconds / 2.0, preferredTimescale: duration.timescale)
            
{'fraction_non_alphanumeric': 0.07749749567434659, 'fraction_numerical': 0.004189053820234951, 'mean_word_length': 1.9737340915245059, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4132009', 'n_tokens_mistral': 2807, 'n_tokens_neox': 2735, 'n_words': 686}