//
//  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 {
                var ecaAreas = ecaData.ecaArea
                for ares in ecaData.ecaArea {
                    var eca = ares.value
                    eca.isEnable = false
                    ecaAreas.updateValue(eca, forKey: eca.areaId)
                }
                for ecaList in res {
                    if var value = ecaAreas[ecaList.areaId]{
                        value.id = ecaList.id
                        value.userName = ecaList.userName
                        value.isEnable = true
                        value.swNotice = ecaList.noticeRange
                        value.swStart  = ecaList.startRange
                        value.swFinish = ecaList.finishRange
                        value.lastUpdateTime = ecaList.lastUpdateTime
                        if ecaList.status & serverRunning == serverRunning {
                            value.isRunning = true
                            value.status = setEcaServer(status: ecaList.status)
                        } else {
                            value.isRunning = false
                            value.status = EcaState.register
                        }
                        ecaAreas.updateValue(value, forKey: ecaList.areaId)
                    }
                }
                for ares in ecaAreas{
                    ecaData.setEcaArea(key: ares.value.areaId, value: ares.value)
                }
            }
        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
    }
}
