<commit_before>//
//  DKPhotoBaseImagePreviewVC.swift
//  DKPhotoGallery
//
//  Created by ZhangAo on 15/09/2017.
//  Copyright © 2017 ZhangAo. All rights reserved.
//

import UIKit
import Photos
import AssetsLibrary
import FLAnimatedImage

open class DKPhotoBaseImagePreviewVC: DKPhotoBasePreviewVC {

    // MARK: - QR Code
    
    private func detectStringFromImage() -> String? {
        guard let contentView = self.contentView as? DKPhotoImageView else { return nil }
        
        guard let targetImage = contentView.image ?? contentView.animatedImage?.posterImage else {
            return nil
        }
        
        if let result = self.detectStringFromCIImage(image: CIImage(image: targetImage)!) {
            return result
        } else {
            return nil
        }
    }
    
    private func detectStringFromCIImage(image: CIImage) -> String? {
        let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [
            CIDetectorAccuracy : CIDetectorAccuracyHigh
            ])
        
        if let detector = detector {
            let features = detector.features(in: image)
            if let feature = features.first as? CIQRCodeFeature {
                return feature.messageString
            } else {
                return nil
            }
        } else {
            return nil
        }
    }
    
    private func previewQRCode(with result: String) {
        if let URL = URL(string: result), let _ = URL.scheme, let _ = URL.host {
            let resultVC = DKPhotoWebVC()
            resultVC.urlString = result
            self.navigationController?.pushViewController(resultVC, animated: true)
        } else {
            let resultVC = DKPhotoQRCodeResultVC(result: result)
            self.navigationController?.pushViewController(resultVC, animated: true)
        }
    }
    
    // MARK: - Save Image
    
    private func saveImageToAlbum() {
        guard let contentView = self.contentView as? DKPhotoImageView else { return }
        
        PHPhotoLibrary.requestAuthorization { (status) in
            DispatchQueue.main.async(execute: {
                switch status {
                case .authorized:
                    if let animatedImage = contentView.animatedImage {
                        ALAssetsLibrary().writeImageData(toSavedPhotosAlbum: animatedImage.data, metadata: nil, completionBlock: { (newURL, error) in
                            self.showImageSaveResult(with: error)
                        })
                    } else if let imageURL = self.item.imageURL, imageURL.isFileURL, let data = try? Data(contentsOf: imageURL) {
                        ALAssetsLibrary().writeImageData(toSavedPhotosAlbum: data, metadata: [:], completionBlock: { (newURL, error) in
                            self.showImageSaveResult(with: error)
                        })
                    } else if let image = contentView.image {
                        UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.image(_:didFinishSavingWithError:contextInfo:)), nil)
                    }
                case .restricted:
                    fallthrough
                case .denied:
                    self.showTips(DKPhotoGalleryResource.localizedStringWithKey("preview.image.saveImage.permission.error"))
                default:
                    break
                }
            })
        }
    }
    
    @objc func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) {
        self.showImageSaveResult(with: error)
    }
    
    func showImageSaveResult(with error: Error?) {
        if let error = error {
            self.showTips(error.localizedDescription)
        } else {
            self.showTips(DKPhotoGalleryResource.localizedStringWithKey("preview.image.saveImage.result.success"))
        }
    }
    
    // MARK: - DKPhotoBasePreviewDataSource
    
    override public func createContentView() -> UIView {
        let contentView = DKPhotoImageView()
        return contentView
    }
    
    open override func prepareForReuse() {
        super.prepareForReuse()
        
        (self.contentView as! DKPhotoImageView).image = nil
        (self.contentView as! DKPhotoImageView).animatedImage = nil
    }
    
    override public func updateContentView(with content: Any) {
        guard let contentView = self.contentView as? DKPhotoImageView else { return }
        
        if let data = content as? Data {<commit_msg>Fixed a problem that would cause image shows in incorrect orientation.<commit_after>//
//  DKPhotoBaseImagePreviewVC.swift
//  DKPhotoGallery
//
//  Created by ZhangAo on 15/09/2017.
//  Copyright © 2017 ZhangAo. All rights reserved.
//

import UIKit
import Photos
import AssetsLibrary
import FLAnimatedImage

open class DKPhotoBaseImagePreviewVC: DKPhotoBasePreviewVC {

    // MARK: - QR Code
    
    private func detectStringFromImage() -> String? {
        guard let contentView = self.contentView as? DKPhotoImageView else { return nil }
        
        guard let targetImage = contentView.image ?? contentView.animatedImage?.posterImage else {
            return nil
        }
        
        if let result = self.detectStringFromCIImage(image: CIImage(image: targetImage)!) {
            return result
        } else {
            return nil
        }
    }
    
    private func detectStringFromCIImage(image: CIImage) -> String? {
        let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [
            CIDetectorAccuracy : CIDetectorAccuracyHigh
            ])
        
        if let detector = detector {
            let features = detector.features(in: image)
            if let feature = features.first as? CIQRCodeFeature {
                return feature.messageString
            } else {
                return nil
            }
        } else {
            return nil
        }
    }
    
    private func previewQRCode(with result: String) {
        if let URL = URL(string: result), let _ = URL.scheme, let _ = URL.host {
            let resultVC = DKPhotoWebVC()
            resultVC.urlString = result
            self.navigationController?.pushViewController(resultVC, animated: true)
        } else {
            let resultVC = DKPhotoQRCodeResultVC(result: result)
            self.navigationController?.pushViewController(resultVC, animated: true)
        }
    }
    
    // MARK: - Save Image
    
    private func saveImageToAlbum() {
        guard let contentView = self.contentView as? DKPhotoImageView else { return }
        
        PHPhotoLibrary.requestAuthorization { (status) in
            DispatchQueue.main.async(execute: {
                switch status {
                case .authorized:
                    if let animatedImage = contentView.animatedImage {
                        ALAssetsLibrary().writeImageData(toSavedPhotosAlbum: animatedImage.data, metadata: nil, completionBlock: { (newURL, error) in
                            self.showImageSaveResult(with: error)
                        })
                    } else if let imageURL = self.item.imageURL, imageURL.isFileURL, let data = try? Data(contentsOf: imageURL) {
                        ALAssetsLibrary().writeImageData(toSavedPhotosAlbum: data, metadata: [:], completionBlock: { (newURL, error) in
                            self.showImageSaveResult(with: error)
                        })
                    } else if let image = contentView.image {
                        UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.image(_:didFinishSavingWithError:contextInfo:)), nil)
                    }
                case .restricted:
                    fallthrough
                case .denied:
                    self.showTips(DKPhotoGalleryResource.localizedStringWithKey("preview.image.saveImage.permission.error"))
                default:
                    break
                }
            })
        }
    }
    
    @objc func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) {
        self.showImageSaveResult(with: error)
    }
    
    func showImageSaveResult(with error: Error?) {
        if let error = error {
            self.showTips(error.localizedDescription)
        } else {
            self.showTips(DKPhotoGalleryResource.localizedStringWithKey("preview.image.saveImage.result.success"))
        }
    }
    
    // MARK: - DKPhotoBasePreviewDataSource
    
    override public func createContentView() -> UIView {
        let contentView = DKPhotoImageView()
        return contentView
    }
        
    override public func updateContentView(with content: Any) {
        guard let contentView = self.contentView as? DKPhotoImageView else { return }
        
        if let data = content as? Data {
{'fraction_non_alphanumeric': 0.07767210144927536, 'fraction_numerical': 0.002717391304347826, 'mean_word_length': 1.9036817882971728, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '5831919', 'n_tokens_mistral': 2374, 'n_tokens_neox': 2231, 'n_words': 535}