//
// Copyright (c) WhatsApp Inc. and its affiliates.
// All rights reserved.
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.
//

import UIKit

class WebPManager {

    static let shared: WebPManager = WebPManager()

    func isAnimated(webPData data: Data) -> Bool {
        guard let decoder = YYImageDecoder(data: data, scale: 1.0) else {
            return false
        }

        return decoder.frameCount > 1
    }

    func decode(webPData data: Data) -> UIImage? {
        guard let decoder = YYImageDecoder(data: data, scale: 1.0) else {
            return nil
        }
        
        return decoder.frame(at: 0, decodeForDisplay: true)?.image
    }

    func encode(pngData data: Data) -> Data? {
        guard let encoder = YYImageEncoder(type: YYImageType.webP) else {
            return nil
        }

        encoder.addImage(with: data, duration: 0.0)

        return encoder.encode()
    }
    
    func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
        let size = image.size

        let widthRatio  = targetSize.width  / image.size.width
        let heightRatio = targetSize.height / image.size.height

        // Figure out what our orientation is, and use that to form the rectangle
        var newSize: CGSize
        if(widthRatio > heightRatio) {
            newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
        } else {
            newSize = CGSize(width: size.width * widthRatio,  height: size.height * widthRatio)
        }

        // This is the rect that we've calculated out and this is what is actually used below
        let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)

        // Actually do the resizing to the rect using the ImageContext stuff
        UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
        image.draw(in: rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return newImage!
    }
}
