//
//  Tool.swift
//  OrderScheduling
//
//  Created by 中道 on 2023/8/10.
//

import Foundation
import UIKit
import AVFoundation

public let TOOL = Tool.default

open class Tool {
    public static let `default` = Tool()
    func getDuration(url:URL) -> CMTime {
        let urlAsset = AVURLAsset(url: url)
        var duration : CMTime = CMTime.zero
//        if #available(iOS 16.0, *) {
//            do {
//                duration = try await urlAsset.load(.duration)
//            }catch{
//            }
//        }else{
            duration = urlAsset.duration
//        }
        return duration
    }
    
    public func getVideoDateString(duration:Int) -> String {
        let min = duration / 60
        var minStr = ""
        if min > 9 {
            minStr = String(min)
        }else {
            minStr = "0"+String(min)
        }
        
        let sec = duration % 60
        var secStr = ""
        if sec > 9 {
            secStr = String(sec)
        }else{
            secStr = "0"+String(sec)
        }
        
        return minStr+":"+secStr
    }
    
    public func call(phone:String) {
        guard let url  = URL(string: "tel:\(phone)") else {
            return
        }

        if #available(iOS 10.0, *) {
            UIApplication.shared.open(url, options: [:],completionHandler: nil)
        } else {
            UIApplication.shared.openURL(url)
        }
    }
    
    public func getDateStringCompareWithNow(dateFormat:String,dateString:String) -> String {
        let format = DateFormatter()
        format.dateFormat = dateFormat
        let date = format.date(from: dateString) ?? Date()
        let dateNow = Date()
        let dateNowString = format.string(from: dateNow)
        let dateYMD = dateString.components(separatedBy: " ").first
        let dateNowYMD = dateNowString.components(separatedBy: " ").first
        if dateYMD == dateNowYMD {
            let diffInterval = dateNow.timeIntervalSince1970 - date.timeIntervalSince1970
            var combineString : String
            if diffInterval >= 3600 {
                combineString = String(Int(diffInterval / 3600))+"小时前"
            }else if diffInterval >= 60 {
                combineString = String(Int(diffInterval / 60))+"分钟前"
            }else{
                combineString = String(Int(diffInterval))+"秒前"
            }
            return combineString
        }
        return dateString
    }
}
