//
//  SessionTaskList.swift
//  Sailassist
//
//  Created by 三浦薫巳 on 2023/11/15.
//

import Foundation
import SwiftUI

class SessionTaskList : ObservableObject {
    @Published var status = false
    // シングルトン宣言
    static let OnlyOne = SessionTaskList()

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

    /**
     * タスクリスト取得
     */
    func RequestGetTaskList(_ completion: @escaping ((Result<Data, APIError>)) -> Void) {
        print(debug: "calld")
        if Calling {
            return
        }
        Calling = true

        // リクエストURLの組み立て
        let id = Preferences.shipId
        if id != 0 {
            var url_string : String = HttpRequestType.TaskList.rawValue
            url_string = url_string.replacingOccurrences(of: "XXXXX", with: String(id))
            guard let req_url = URL(string : url_string) else {
                Calling = false
                return
            }

            serverSession.getJson(req_url, completion: completion)
        }
    }

    /**
     * タスク保存
     */
    func RequestPostTaskList(_ eca : ReqTaskList, completion: @escaping ((Result<Data, APIError>)) -> Void) {
        print(debug: "calld")
        if Calling {
            return
        }
        Calling = true

        // リクエストURLの組み立て
        let id = Preferences.shipId
        if id != 0 {
            var url_string : String = HttpRequestType.TaskList.rawValue
            url_string = url_string.replacingOccurrences(of: "XXXXX", with: String(id))
            guard let req_url = URL(string : url_string) else {
                Calling = false
                return
            }

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

    /**
     * タスク削除
     */
    func RequestDeleteTaskList(_ ecaId : Int, completion: @escaping ((Result<Data, APIError>)) -> Void) {
        print(debug: "calld")
        if Calling {
            return
        }
        Calling = true

        // リクエストURLの組み立て
        let id = Preferences.shipId
        if id != 0 {
            let strId = String(id) + "/" + String(ecaId)
            var url_string : String = HttpRequestType.TaskList.rawValue
            url_string = url_string.replacingOccurrences(of: "XXXXX", with: strId)
            guard let req_url = URL(string : url_string) else {
                Calling = false
                return
            }

            serverSession.deleteJson(req_url, completion: completion)
        }
    }
}
