//
//  InputIdPassWordView.swift
//  forShip
//
//  Created by Mamoru Sugita on 2023/10/13.
//

import SwiftUI
import Combine

struct InputIdPassWordView: View {
    @Binding var isLogin: Bool
    @Binding var viewMode : LoginViewMode
    @Binding var param : LoginViewParam
    @Binding var isProgressView : Bool
    @Binding var isAlert : Bool
    @Binding var alertType: AlertType
    @State private var isUserNmaeEmpty = false
    @State private var isIdPassWordEmpty = false
    @State var timer :Timer?

    let sessionLogin = SessionLogin()

    var body: some View {
        VStack{
            VStack(alignment: .leading, spacing: 0) {
                HStack(spacing: 0){
                    Image("account")
                        .resizable()
                        .frame(width: 22, height: 22)
                        .padding(EdgeInsets(top: 14, leading: 8, bottom: 13, trailing: 18))

                    TextField(
                        "",
                        text: $param.shipId,
                        prompt: Text("Ship ID")
                            .font(FontStyle.DefaultText.font)
                            .foregroundColor(ColorSet.BodyDescriptiion.color)                    )
                    .frame(height: 49)
                    .padding(.zero)
                    .autocapitalization(.none)
                }

                Divider()
                    .frame(height: 1)
                    .background(ColorSet.LineColor03.color)

                HStack(spacing: 0){
                    Image("password")
                        .resizable()
                        .frame(width: 22, height: 22)
                        .padding(EdgeInsets(top: 14, leading: 8, bottom: 13, trailing: 18))
                    SecureField(
                        "",
                        text: $param.password,
                        prompt: Text("Password")
                            .font(FontStyle.DefaultText.font)
                            .foregroundColor(ColorSet.BodyDescriptiion.color)
                    )
                    .frame(height: 49)
                    .padding(.zero)
                }
                .padding(.top, 16)


                Divider()
                    .frame(height: 1)
                    .background(ColorSet.LineColor03.color)
            }

            Button(action: {
                if param.shipId.isEmpty || param.password.isEmpty {
                    isIdPassWordEmpty = true
                } else {
                    isAlert = false
                    isProgressView = true
                    let login = ReqLogin(Id: param.shipId, Password: param.password)
                    sessionLogin.RequestLogin(login, completion: responseLogin)
                }
            }, label: {
                Text("Sign In")
                    .font(FontStyle.TitleS.font)
                    .frame(height: 60)
                    .frame(maxWidth: .infinity)
                    .foregroundColor(ColorSet.ButtonText.color)
                    .background(ColorSet.LoginBk01.color)
            })
            .alert(isPresented: $isIdPassWordEmpty, content: {
                Alert(title: Text("error"),
                      message: Text("Ship ID or Password is incorrect.")
                )
            })
            .padding(.top, 40)
        }
        .padding(EdgeInsets(top: 26, leading: 20, bottom: 40, trailing: 20))
        .background(ColorSet.LoginBk02.color)
        .padding(.horizontal, 30)
    }

    func responseLogin(result: Result<Data, APIError>) {
        print(debug: "calld")
        switch result {
        case .success(let resultData):
            let serverSession = ServerSession()
            let resjson = serverSession.fromJSON(resultData: resultData, resltType: ResLogin.self)
            if let res = resjson {
                SharingData.my.id = res.id
                SharingData.my.shipName = res.shipName
                SharingData.my.imo = res.imo
                SharingData.my.mmsi = res.mmsi

                Preferences.shipId = res.shipId
            }

            Preferences.lastLoginDate_Int64 = DateTextLib.Date2UnixTime(date: Date())
            viewMode = .InputUserName

//            let ecaArea = EcaArea()
//            ecaArea.start()

            timer = Timer.scheduledTimer(withTimeInterval: 30.0, repeats: true) { _ in
                print(debug: "called timer")
                let eca = EcaTask()
                eca.start()

                let message = GetMessage()
                message.start()

                let route = MonitoringRoute()
                route.start()

                let ecaList = GetEcaList()
                ecaList.start()

                let pushHistory = GetPushHistory()
                pushHistory.start()
            }
            timer?.fire()

        case .failure(let errorCode):
            print(debug: errorCode)
            isLogin = false
            isAlert = true
            alertType = .loginFailure
            break
        }
        isProgressView = false
    }
}

#Preview {
    InputIdPassWordView(isLogin: .constant(false), viewMode: .constant(.InputIdPassword), param: .constant(LoginViewParam()), isProgressView: .constant(false), isAlert: .constant(false), alertType: .constant(.loginFailure))
}
