//
//  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?

    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.userName,
                        prompt: Text("Please set user name.")
                            .font(FontStyle.SupplementText.font)
                            .foregroundColor(ColorSet.BodyDescriptiion.color)
                    )
                    .frame(height: 49)
                    .padding(.zero)
                }

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

            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
                    Preferences.UserName = param.userName
                    let login = ReqLogin(Id: param.shipId, Password: param.password, DeviceId: param.deviceid, UserName: param.userName)
                    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: $isEmptyAlert) {
                return Alert(title: Text("Error"),
                             message: Text("User Nmae not entered.")
                )
            }
            .padding(.top, 40)
        }
        .padding(EdgeInsets(top: 21, leading: 20, bottom: 32, 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

                let notification = NotificationTags()
                notification.addTags()
            }

            Preferences.Id = param.shipId
            Preferences.Password = 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()

                let ecaList = GetEcaList()
                ecaList.start()

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

            isProgressView = false
            isLogin = true
            isAlert = false

            let manual = GetManualUrl()
            manual.start()

        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))
}
