//
//  GetEcaList.swift
//  Sailassist
//
//  Created by 三浦薫巳 on 2023/11/28.
//

import Foundation
import SwiftUI

class GetEcaList {
    @ObservedObject var ecaData = SharingData.eca
    var sessionTaskList = SessionTaskList()

    func start() {
        print(debug: "called")
        sessionTaskList.RequestGetTaskList(responseGetTaskList)
    }

    private func responseGetTaskList(result: Result<Data, APIError>) {
        print(debug: "called")
        switch result {
        case .success(let resultData):
            let serverSession = ServerSession()
            let resjson = serverSession.fromJSON(resultData: resultData, resltType: [ReqTaskList].self)
            if let res = resjson {
                for ecaList in res {
                    if var value = ecaData.ecaArea[ecaList.taskName] {
                        value.isEnable = true
                        value.swNotice = ecaList.noticeRange
                        value.swStart  = ecaList.startRange
                        value.swFinish = ecaList.finishRange
                        if ecaList.status & serverRunning == serverRunning {
                            value.isRunning = true
                            value.status = setEcaServer(status: ecaList.status)
                        } else {
                            value.isRunning = false
                            value.status = EcaState.register
                        }
                        ecaData.ecaArea.updateValue(value, forKey: ecaList.taskName)
                    }
                }
            }
        case .failure(let errorCode):
            print(debug: errorCode)
            break
        }
    }

    private func setEcaServer(status: Int) -> EcaState {
        var state = EcaState.register
        switch status {
        case serverRunning:
            state = EcaState.running
        case serverNoticePass:
            state = EcaState.noticePass
        case serverStartPass:
            state = EcaState.startPass
        case serverFinishPass:
            state = EcaState.finishPass
        case serverEnd:
            state = EcaState.end
        case serverIncomplete:
            state = EcaState.incomplete
        case serverCancel:
            state = EcaState.cancel
        default:
            state = EcaState.register
        }

        return state
    }
}
