//
//  MyCodeVC.swift
//  WoWonder
//
//  Created by iMac on 25/05/24.
//  Copyright © 2024 ScriptSun. All rights reserved.
//

import UIKit
import SDWebImage

class MyCodeVC: UIViewController {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var userImage: UIImageView!
    @IBOutlet weak var userNameLabel: UILabel!
    @IBOutlet weak var qrCodeImage: UIImageView!
    
    // MARK: - Properties
    
    var parentContorller: QRCodeVC!
    
    // MARK: - View Life Cycles

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        self.initialConfig()
    }
    
    // MARK: - Selectors
    
    // Share to Button Action
    @IBAction func shareToButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let name = URL(string: AppInstance.instance.userProfile?.url ?? "") {
            let objectsToShare = [name]
            let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
            self.present(activityVC, animated: true, completion: nil)
        }
    }
    
    // Save Button Action
    @IBAction func saveButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        let qrCodeImage = self.generateQRCodeImage(url: AppInstance.instance.userProfile?.url ?? "", scale: 10.0, padding: 20.0)
        UIImageWriteToSavedPhotosAlbum(qrCodeImage, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.setData()
    }
    
    static func myCodeVC() -> MyCodeVC {
        let newVC = R.storyboard.dashboard.myCodeVC()
        return newVC!
    }
    
    // Set Data
    func setData() {
        let url = URL(string: AppInstance.instance.userProfile?.avatar ?? "")
        let indicator = SDWebImageActivityIndicator.medium
        self.userImage.sd_imageIndicator = indicator
        DispatchQueue.global(qos: .userInteractive).async {
            self.userImage.sd_setImage(with: url, placeholderImage: UIImage(named: ""))
        }
        self.userNameLabel.text = "@" + (AppInstance.instance.userProfile?.username ?? "")
        self.qrCodeImage.image = self.generateQRCodeImage(url: AppInstance.instance.userProfile?.url ?? "", scale: 10, padding: 20.0)
    }
    
    func generateQRCodeImage(url: String, scale: Double, padding: Double) -> UIImage {
        guard let data = url.data(using: .utf8), let filter = CIFilter(name: "CIQRCodeGenerator") else {
            return UIImage(systemName: "xmark") ?? UIImage()
        }

        filter.setValue(data, forKey: "inputMessage")
        filter.setValue("M", forKey: "inputCorrectionLevel")

        if let qrCodeImage = filter.outputImage {
            let scaleX = scale
            let scaleY = scale
            let transformedImage = qrCodeImage.transformed(by: CGAffineTransform(scaleX: CGFloat(scaleX), y: CGFloat(scaleY)))

            let imageSize = transformedImage.extent.size
            let newImageSize = CGSize(width: imageSize.width + padding * 2, height: imageSize.height + padding * 2)
            let newImageRect = CGRect(x: 0, y: 0, width: newImageSize.width, height: newImageSize.height)

            UIGraphicsBeginImageContextWithOptions(newImageSize, false, 0)
            let context = UIGraphicsGetCurrentContext()!
            context.setFillColor(UIColor.white.cgColor)
            context.fill(newImageRect)

            let qrCodeRect = CGRect(x: padding, y: padding, width: imageSize.width, height: imageSize.height)
            let uiImage = UIImage(ciImage: transformedImage)
            uiImage.draw(in: qrCodeRect)

            let paddedQRCodeImage = UIGraphicsGetImageFromCurrentImageContext()!
            UIGraphicsEndImageContext()

            return paddedQRCodeImage
        }
        return UIImage(systemName: "xmark") ?? UIImage()
    }

    @objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
        if let error = error {
            print("Error saving image: \(error.localizedDescription)")
        } else {
            self.view.makeToast("Image saved in gallery")
        }
    }
    
}
