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

import SwiftUI

struct InputUserNameView: View {
    @ObservedObject var sessionLogin: SessionLogin = SessionLogin()
    @Binding var isLogin: Bool
    @Binding var param: LoginViewParam
    @Binding var viewMode : LoginViewMode
    @Binding var isProgressView : Bool
    @Binding var isAlert : Bool
    @Binding var alertType: AlertType
    @State private var isEmptyAlert = false
    @State var timer :Timer?
    let itemHPadding: Double = 16
    let dialogBottomPadding: Double = 32
    let textFieldHeight: Double = 40
    let inputAreaHeight: Double = 150
    let dialogHeight: CGFloat = 250
    let dialogWidth = UIScreen.main.bounds.width - 32

    var body: some View {
        HStack {
            Spacer()
                .frame(width: itemHPadding)
            VStack{
                Spacer()

                VStack(alignment: .leading) {
                    Text("JRC Ship")
                        .padding(.leading, 4)
                        .bold()
                        .foregroundColor(.white)

                    HStack{
                        Image("account")
                            .padding(.horizontal, 4)
                            .foregroundColor(.white)
                        TextField(
                            "",
                            text: $param.userName,
                            prompt: Text("Please set user name")
                                .foregroundColor(.white)
                        )
                        .frame(height: textFieldHeight)
                        .padding(.trailing)
                        .foregroundColor(.white)
                    }

                    Divider()
                        .frame(height: 2)
                        .background(Color(.white))
                }
                .frame(height: inputAreaHeight)

                Spacer()

                Button(action: {
                    if param.userName.isEmpty {
                        isEmptyAlert = true
                    } else {
                        print(debug: "signin: id(\(param.shipId)), pass(\(param.password)), name(\(param.userName))")
                        isAlert = false
                        isProgressView = true
                        let login = ReqLogin(Id: param.shipId, Password: param.password)
                        sessionLogin.RequestLogin(login, completion: responseLogin)
                        Preferences.UserName = param.userName
                    }
                }, label: {
                    Text("Sign In")
                        .frame(height: 50)
                        .frame(maxWidth: .infinity)
                        .foregroundColor(ColorSet.ButtonText.color)
                        .background(ColorSet.PrimaryActiveIcon.color)
                })
                .alert(isPresented: $isEmptyAlert) {
                    return Alert(title: Text("error"),
                                 message: Text("User Nmae not entered.")
                    )
                }
                Spacer()
                    .frame(height: dialogBottomPadding)
            }

            Spacer()
                .frame(width: itemHPadding)
        }
        .frame(width: dialogWidth, height: dialogHeight)
        .background(ColorSet.BackgroundSecondary.color)
    }

    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.shipId = res.shipId
                SharingData.My.shipName = res.shipName
                SharingData.My.imo = res.imo
                SharingData.My.mmsi = res.mmsi
            }

            Preferences.ShipId = param.shipId
            Preferences.ShipPassword = param.password
            Preferences.lastLoginDate_Int64 = DateTextLib.Date2UnixTime(date: Date())

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

                let message = GetMessage()
                message.start()

                let route = MonitoringRoute()
                route.start()
            }

            isProgressView = false
            isLogin = true
            isAlert = false

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

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