//
//  SessionLogin.swift
//  Sailassist
//
//  Created by 三浦薫巳 on 2023/10/26.
//

import Foundation
import SwiftUI
import CoreLocation

class SessionLogin : ObservableObject, ServerAccessDelegate {
    @Published var status = false
    // シングルトン宣言
    static let OnlyOne = SessionLogin()
    var sharingData = SharingData.shared

    private var serverSession = ServerSession()
    private var Calling : Bool = false      // 通信中

    /**
     * ログイン
     *  - Parameters:
     *    - login: ログイン情報
     */
    func RequestLogin(_ login : ReqLogin, completion: @escaping ((Result<Data, APIError>)) -> Void) {
        print(debug: "タスクの実行:EcaTask 10")
        print(debug: "called")
        if Calling {
            return
        }
        Calling = true

        // リクエストURLの組み立て
        let url_string : String = HttpRequestType.RegisterLogin.rawValue
        guard let req_url = URL(string : url_string) else {
            Calling = false
            return
        }

        if let postdata = serverSession.toJSON(login) {
            serverSession.postJson(req_url, postdata, completion: completion)
        }
        else {
            Calling = false
            return
        }
    }

    func RequestLogin(_ login : ReqLogin) {
        print(debug: "タスクの実行:EcaTask 2")
        if Calling {
            return
        }
        Calling = true
        serverSession.delegate = self

        // リクエストURLの組み立て
        let url_string : String = HttpRequestType.RegisterLogin.rawValue
        guard let req_url = URL(string : url_string) else {
            Calling = false
            return
        }

        if let postdata = serverSession.toJSON(login) {
            serverSession.postJson(req_url, postdata)
        }
        else {
            Calling = false
            return
        }
    }

    // エラーデリゲータ
    func serverErrorResponse(errorCode: APIError) {
        print(debug: "タスクの実行:EcaTask 6")
        print(debug: "called: \(errorCode) \n")
        Calling = false
    }

    // ノーマルデリゲータ
    func serverNormalResponse(resultData: Data) {
        print(debug: "タスクの実行:EcaTask 4")
        let resjson = serverSession.fromJSON(resultData: resultData, resltType: ResLogin.self)
//        let ecaArea = sharingData.ecaArea.map{ $0.1 }.filter{ $0.isRunning == true }
//        if let ecaArea = ecaArea[0] {
//            print(debug: "called")
        SharingData.My.location?.latitude = 35.0
        SharingData.My.location?.longitude = 135.0
        var distance = 0.0
        if let nowlocation = SharingData.My.location {
            distance = LocationCalculation.checkPolyline(objPos: iceland, shipPos: nowlocation)
        }
        print(debug: "called: \(distance) \n")
        Calling = false
    }
}
