//
//  PTAssetManager.swift
//  iOSPrinterDemo
//
//  Created by ios on 2019/4/24.
//  Copyright © 2019 Mellow. All rights reserved.
//

import UIKit
import Photos

class PTAssetManager: NSObject {

    static func scaleSourceImage(image:UIImage, width:CGFloat, height:CGFloat) -> UIImage {
        
        UIGraphicsBeginImageContext(CGSize.init(width: width, height: height))
        image.draw(in: CGRect.init(x: 0, y: 0, width: width, height: height))
        guard let scaleImage = UIGraphicsGetImageFromCurrentImageContext() else {
            return UIImage.init()
        }
        UIGraphicsEndImageContext()
        return scaleImage
    }
    
    static func scaleImageForWidth(image:UIImage, width:CGFloat) -> UIImage {
        
        let imageW = image.size.width
        let imageH = image.size.height
        var maxH : CGFloat = 0
        
        if imageW > width {
            maxH = width * imageH / imageW
            return self.scaleSourceImage(image: image, width: width, height: maxH)
        }else {
            return image
        }
        
    }
    
    static func scaleImageForHeight(image:UIImage, height:CGFloat) -> UIImage {
        
        let imageW = image.size.width
        let imageH = image.size.height
        var maxW : CGFloat = 0
        
        if imageH > height {
            maxW = height * imageW / imageH
            return self.scaleSourceImage(image: image, width: maxW, height: height)
        }else {
            return image
        }
        
    }
    
    static func loadImage(with asset:PHAsset, closure:@escaping ((UIImage?)->(Void))) {
        
        let imageRequest = PHImageRequestOptions()
        imageRequest.resizeMode = .exact
        imageRequest.deliveryMode = .opportunistic
        
        PHImageManager.default().requestImageData(for: asset, options: imageRequest) { (data, uti, orientation, info) in
            
            guard let tempInfo = info else { return }
            
            guard let isCloud = tempInfo[PHImageResultIsInCloudKey] as? Bool else { return }
            if isCloud {
                
                let initialRequestOption = PHImageRequestOptions()
                initialRequestOption.resizeMode = .exact
                initialRequestOption.deliveryMode = .opportunistic
                initialRequestOption.isNetworkAccessAllowed = true
                
                initialRequestOption.progressHandler = { (progress, error, stop, info) in
                    DispatchQueue.main.async {
                        if error == nil {
                            
                            SVProgressHUD.showProgress(Float.init(progress), status: NSLocalizedString("Image loading...", comment: ""))
                            if progress == 1 {
                                SVProgressHUD.dismiss()
                            }
                        }else {
                            SVProgressHUD.showError(withStatus: NSLocalizedString("Failed to get iCloud image, please check network status", comment: ""))
                        }
                    }
                }
                
                PHImageManager.default().requestImageData(for: asset, options: initialRequestOption, resultHandler: { (data, uti, orientation, info) in
                    guard let tempData = data else { return }
                    guard let image = UIImage.init(data: tempData) else { return }
                    closure(image)
                })
                
            }else {
                
                guard let temp = data else {
                    SVProgressHUD.showError(withStatus: NSLocalizedString("Failed to get image", comment: ""))
                    return
                }
                
                guard let image = UIImage.init(data: temp) else {
                    SVProgressHUD.showError(withStatus: NSLocalizedString("Failed to get image", comment: ""))
                    return
                }
                closure(image)
                
            }
        }
    }
}

extension UIImageView {
    
    var size : CGSize {
        get {
            return self.bounds.size
        }
    }
    
    func loadImage(with asset:PHAsset) {
        self.loadImage(with: asset, targetSize: CGSize.init(width: self.bounds.width, height: self.bounds.height))
    }
    
    func loadImage(with asset:PHAsset,targetSize:CGSize) {
        let imageRequest = PHImageRequestOptions()
        imageRequest.isSynchronous = true
        imageRequest.resizeMode = .exact
        imageRequest.deliveryMode = .opportunistic
        
        PHImageManager.default().requestImage(for: asset, targetSize: CGSize.init(width: targetSize.width * PRTScale, height: targetSize.height * PRTScale), contentMode: .aspectFill, options: imageRequest) { (requestImage, info) in
            self.image = requestImage
            
        }
    }
    
    
}
