//
//  DownloadButton.swift
//  ColorfulWallpaper
//
//  Created by nkl on 2024/9/10.
//

import Foundation
import Kingfisher

enum DownloadButtonState {
    case idle(isAnimate: Bool)
    case loading
    case downloading
    case pause
    case retry
    case done

    var imageName: String {
        switch self {
        case let .idle(isAnimate):
            if isAnimate {
                return "download"
            } else {
                return "ic_download"
            }
        case .loading:
            return ""
        case .downloading:
            return ""
        case .pause:
            return "ic_download_pause"
        case .retry:
            return "ic_retry"
        case .done:
            return "icon_more"
        }
    }
}

class DownloadButton: UIControl {
    
    lazy var adTag: UIImageView = {
        let tag = UIImageView(image: UIImage(named: "ic_tag"))
        tag.isHidden = false
        return tag
    }()
    
    /// 下载状态
    var downloadState: DownloadButtonState = .idle(isAnimate: false) {
        didSet {
            setStateForButton()
        }
    }

    lazy var loadingView: UIImageView = {
        let img = UIImageView(image: UIImage(named: "ic-rotate-loading"))
        img.isHidden = true
        return img
    }()

    /// 进度条
    lazy var progressView: CWCustomProgressView = {
        let progress = CWCustomProgressView()
        progress.isHidden = true
        progress.isUserInteractionEnabled = false
        return progress
    }()

    lazy var stateImageView: AnimatedImageView = AnimatedImageView()

    override init(frame: CGRect) {
        super.init(frame: frame)
        addChildren()
        makeConstraints()
    }

    func addChildren() {
        addSubview(progressView)
        addSubview(stateImageView)
        addSubview(loadingView)
        addSubview(adTag)
    }

    func makeConstraints() {
        
        adTag.snp.makeConstraints { make in
            make.centerX.equalToSuperview().offset(13)
            make.centerY.equalToSuperview().offset(-10)
            make.width.equalTo(14.4)
            make.height.equalTo(12)
        }
        
        progressView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.height.equalTo(40)
        }

        stateImageView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.height.equalTo(24)
        }

        loadingView.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
    }

    private func startLoadingAnimation() {
        // 1.创建动画
        let animation = CABasicAnimation(keyPath: "transform.rotation.z")
        // 2.设置动画属性
        animation.fromValue = 0 // 开始角度
        animation.toValue = Double.pi * 2 // 结束角度
        animation.repeatCount = .greatestFiniteMagnitude // 重复次数
        animation.duration = 1
        // 动画完成后自动重新开始,默认为NO
        animation.autoreverses = false
        // 默认是true，切换到其他控制器再回来，动画效果会消失，需要设置成false，动画就不会停了
        animation.isRemovedOnCompletion = false
        loadingView.layer.add(animation, forKey: nil) // 给需要旋转的view增加动画
    }

    func setStateForButton() {
        stateImageView.setLocalizedImage(UIImage.init(named: downloadState.imageName))
        stateImageView.snp.updateConstraints { make in
            make.width.height.equalTo(24)
        }
        switch downloadState {
        case let .idle(animate):
            if !animate {
                stateImageView.setLocalizedImage(UIImage.init(named: downloadState.imageName))
                stateImageView.snp.updateConstraints { make in
                    make.width.height.equalTo(24)
                }
            }else{
//                let path = Bundle.main.path(forResource:downloadState.imageName, ofType:"gif")
//                let url = URL(fileURLWithPath: path!)
//                let resource = Kingfisher.KF.ImageResource(downloadURL: url)
//                stateImageView.kf.setImage(with: resource)
//                stateImageView.snp.updateConstraints { make in
//                    make.width.height.equalTo(24)
//                }
                stateImageView.setLocalizedImage(UIImage.init(named: downloadState.imageName))
                stateImageView.snp.updateConstraints { make in
                    make.width.height.equalTo(24)
                }
            }
            progressView.isHidden = true
            loadingView.isHidden = true
            adTag.isHidden = PurchaseManager.default.isVip
        case .loading:
            adTag.isHidden = true
            progressView.isHidden = true
            loadingView.isHidden = false
            startLoadingAnimation()
        case .downloading:
            adTag.isHidden = true
            progressView.isHidden = false
            progressView.progressTitle.isHidden = false
            loadingView.isHidden = true
        case .pause:
            adTag.isHidden = true
            progressView.isHidden = true
            progressView.progressTitle.isHidden = true
            loadingView.isHidden = true
        case .retry:
            adTag.isHidden = true
            progressView.isHidden = true
            loadingView.isHidden = true
        case .done:
            adTag.isHidden = true
            progressView.isHidden = true
            loadingView.isHidden = true
        }
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
