//
//  AppVersionModel.swift
//  Sailassist
//
//  Created by 三浦薫巳 on 2023/12/26.
//

import Foundation

class AppVersionModel: ObservableObject {
    private var serverSession = ServerSession()
    let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString")

    func start() {
        print(debug: "called")
        versionURL { response in
            print(debug: "called")
            switch response {
            case .success(let resultData):
                print(debug: String(data: resultData, encoding: .utf8) as Any)
                let jsonstr = String(data: resultData, encoding: .utf8)!
                let appData: Data =  jsonstr.data(using: String.Encoding.utf8)!
                do {
                    let json = try JSONSerialization.jsonObject(with: appData, options: [.allowFragments]) as? [String: Any]
                    guard let result = (json?["results"] as? [Any])?.first as? [String: Any],
                          let storeVersion = result["version"] as? String else { return }
                    if let app = self.appVersion as? String {
                        SharingData.my.isUpDate = storeVersion.versionCompare(app) == .orderedDescending
                    }
                } catch {
                    print(error)
                }
            case .failure(let errorCode):
                print(debug: errorCode)
                break
            }
        }
    }

    private func versionURL(_ completion: @escaping ((Result<Data, APIError>)) -> Void) {
        print(debug: "calld")
        let url_string = HttpRequestType.AppInfo.rawValue + "&date=\(Date.init().timeIntervalSince1970)"
        guard let req_url = URL(string : url_string) else {
            return
        }
        serverSession.getJson(req_url, completion: completion)
    }
}

/**
 * Version番号比較
 *  メジャーバージョン・マイナーバージョン・リビジョンバージョン
 *  マイナーバージョン以上が変更された場合
 */
extension String {
    func versionCompare(_ otherVersion: String) -> ComparisonResult {
        let delimiter = "."
        var versionComponents = self.components(separatedBy: delimiter)
        var otherComponents = otherVersion.components(separatedBy: delimiter)

        versionComponents[2] = "0"
        otherComponents[2] = "0"

        return versionComponents.joined(separator: delimiter)
            .compare(otherComponents.joined(separator: delimiter), options: .numeric)
    }
}
