//
//  THUD+CW.swift
//  ColorfulWallpaper
//
//  Created by nkl on 2024/9/23.
//

import Foundation
import UIKit

extension THUD {
    static func showLoading(_ message: String?,
                            cancelHandler: (() -> Void)?) {
        showLoading { config in
            config.blur = true
            config.stateMessage = message
            config.actionTitle = "Cancel".localized()
            config.actionHandler = { _ in
                cancelHandler?()
            }
        }
    }

    static func showLoading(_ state: String?,
                            message: String?) {
        showLoading { config in
            config.blur = true
            config.stateMessage = state
            config.descMessage = message
        }
    }

    static func showLoading(_ stateImage: UIImage?,
                            message: String?,
                            actionHandler: ((Bool) -> Void)?) {
        showLoading { config in
            config.blur = true
            config.stateImage = stateImage
            config.descMessage = message
            config.actionTitle = "Retry".localized()
            config.actionHandler = actionHandler
            config.closeable = true
        }
    }
}

// MARK: loading

public extension THUD {
    static func showLoading() {
        showLoading { config in
            config.backgroundColor = .hexColor("#232327")
            config.minWidth = nil
            config.loadingSize = CGSize(width: 32, height: 32)
        }
    }
}

// MARK: toast

public extension THUD {
    static func toast(_ message: String?,
                      at position: THUD.Position = .top,
                      in view: UIView? = nil,
                      shake: Bool = false) {
        guard let message = message, !message.isEmpty else { return }

        var tipConfig = TipsViewConfig()
        tipConfig.message = message
        tipConfig.background = .hexColor("#2C2B2C")
        tipConfig.textColor = .white
        tipConfig.duration = 3.0
        show(tipConfig, position: position, in: view)

        if shake {
            UIImpactFeedbackGenerator(style: .heavy).impactOccurred()
        }
    }
}

public extension THUD {
    static func showLoading(_ configHandler: ((HUDConfig) -> Void)?) {
        let config = HUDConfig()
        configHandler?(config)

        hide()
        guard let superView = UIApplication.topViewController?.view else {
            return
        }
        show(config, position: .center, in: superView)
    }
}
