package com.example.smart119.views

import android.graphics.Color
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.navigation.fragment.findNavController
import com.example.smart119.API_Helper
import com.example.smart119.AlertDialogUtil
import com.example.smart119.BuildConfig
import com.example.smart119.LocationHelper
import com.example.smart119.LoginManager
import com.example.smart119.LoginManager.tryLoginBody
import com.example.smart119.MyCookieJar
import com.example.smart119.R
import com.example.smart119.TransferManager
import com.example.smart119.databinding.FragmentFirstBinding
import com.example.smart119.datas.SaveLogin

import com.example.smart119.interfaces.RetrofitClient
import com.google.gson.JsonObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.android.material.textfield.TextInputEditText
import okhttp3.Cookie

/**
 * A simple [Fragment] subclass as the default destination in the navigation.
 */
class LoginFragment : Fragment() {

    private var _binding: FragmentFirstBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    private val cookieStore: MutableMap<String, MutableList<Cookie>> = mutableMapOf()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        _binding = FragmentFirstBinding.inflate(inflater, container, false)
        return binding.root
    }

    //현재 창이 보여질 때 호출되는 함수
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        println("login fragment!!")

        val button: Button = view.findViewById(R.id.accessButton)
        button.setBackgroundColor(Color.parseColor("#0971B8"))

        //#region 바로 preference로 로그인 체크
        login_check()
        //#endregion

        binding.accessButton.setOnClickListener {
            val userIdTextInput: TextInputEditText = view.findViewById(R.id.loginIdText); //"kwonkhj01"
            val carNoTextInput: TextInputEditText = view.findViewById(R.id.carNoText);//"70보2495"

            var _inputId = userIdTextInput.text.toString()
            var _inputCarno = carNoTextInput.text.toString()

            var _isPass:Boolean = false;
            // debug용으로, 시작 버튼 눌렀을때 바로 자동 입력
            // region
            if(_inputId.isEmpty()) {
                AlertDialogUtil.showAlert(
                    context = requireContext(),
                    title = "로그인 오류",
                    message = "유저 아이디를 입력해주세요",
                    onPositiveClick = {
                        //로그아웃 처리
                    },
                    onNegativeClick = {

                    }
                )
                _isPass = true;
//                _inputId = "keeys1993"
            }
            else if(_inputCarno.isEmpty()) {
                AlertDialogUtil.showAlert(
                    context = requireContext(),
                    title = "로그인 오류",
                    message = "차량 번호를 입력해주세요",
                    onPositiveClick = {
                        //로그아웃 처리
                    },
                    onNegativeClick = {

                    }
                )
                _isPass = true;
//                _inputCarno = "998마2352"
            }
            // endregion
//            println("login info ${_inputId}, ${_inputCarno}")


            if (!_isPass) {
                LoadingDialog.showDlg(requireContext())

                LoginManager.setLoggedInfo(_inputId, _inputCarno, BuildConfig.APP_VERSION);
                val loginBody = LoginManager.getLoggedInfo();
                println("로그인 정보 ${loginBody["userId"].asString}, ${loginBody["carNo"].asString}, ${loginBody["ver"].asString}")
                RetrofitClient.loginInstance.mLogin(loginBody)
                    .enqueue(loginResponse())
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    private fun login_check() {

        if (SaveLogin.isLoggedIn()) {
            //로그인 상태면 바로 로그인 요청 후 진행
            var _inputId = SaveLogin.getUserId()
            var _inputCarno = SaveLogin.getCarNo()

            if (_inputId == null || _inputId.isEmpty()) return;
            if (_inputCarno == null || _inputCarno.isEmpty()) return;

            println(BuildConfig.APP_VERSION);

            LoadingDialog.showDlg(requireContext())
            LoginManager.setLoggedInfo(_inputId, _inputCarno, BuildConfig.APP_VERSION);
            val loginBody = LoginManager.getLoggedInfo();
            println("로그인 정보 ${loginBody["userId"].asString}, ${loginBody["carNo"].asString}, ${loginBody["ver"].asString}")
            RetrofitClient.loginInstance.mLogin(loginBody).enqueue(loginResponse())
        }

    }



    private fun loginResponse(): Callback<JsonObject> {
        return object : Callback<JsonObject> {
            override fun onResponse(call: Call<JsonObject>, response: Response<JsonObject>) {
                if (response.isSuccessful) {
//                    println("Stored cookies: ${MyCookieJar.getCookies()}")
                    try {
                        val resBody = response.body();
                        val status = resBody?.get("status")?.asString;
                        if (status == "success") {
                            val cookies = response.headers().values("Set-Cookie")
    //                    println("Set-Cookie Headers: $cookies")
                            for (cookie in cookies) {
                                val cookieValue = cookie.split(";")[0] // "sessionId=abc123"만 추출
                                MyCookieJar.setCookie(cookieValue)
    //                        println("Cookie Value: $cookieValue")
                            }
                            LoginManager.setLoggedIn(true);

                            var loginInfo = LoginManager.getLoggedInfo();
                            if (loginInfo != null) {
                                Toast.makeText(
                                    requireActivity(),
                                    "접속 되었습니다. [${loginInfo["userId"].asString}, ${loginInfo["carNo"].asString}]",
                                    Toast.LENGTH_SHORT
                                ).show()
                            }

                            LoadingDialog.hideDlg()

                            //#region 로그인 정보 저장
                            SaveLogin.setLogin(true);
                            SaveLogin.setUserId(loginInfo["userId"].asString);
                            SaveLogin.setCarNo(loginInfo["carNo"].asString);
                            //#endregion

                            RetrofitClient.transferInstance.currentAction().enqueue(currentActionResponse())

//                            moveToHospSearch();
                        }
                        else {
                            AlertDialogUtil.showAlert(
                                context = requireActivity(),
                                title = "접속 실패",
                                message = "접속 아이디와 차량번호를 확인해주세요. [${status}]"
                            )
                            LoadingDialog.hideDlg()
                        }
                    } catch (e: Exception) {
                        println(e.message)
                        LoadingDialog.hideDlg()
                    }

                } else {
                    LoginManager.setLoggedIn(false);
                    var loginInfo:JsonObject = LoginManager.getLoggedInfo();

                    AlertDialogUtil.showAlert(
                        context = requireActivity(),
                        title = "접속 실패",
                        message = "접속 아이디와 차량번호를 확인해주세요. [${loginInfo.get("userId").toString()}, ${loginInfo.get("carNo").toString()}]"
                    )
                    LoadingDialog.hideDlg()
                }
            }

            override fun onFailure(call: Call<JsonObject>, t: Throwable) {
                LoadingDialog.hideDlg()

                AlertDialogUtil.showAlert(
                    context = requireActivity(),
                    title = "접속 실패",
                    message = "네트워크 상태를 확인해주세요. \n" + "${t.message}"
                )

                if (SaveLogin.isLoggedIn()) {
                    val thisView = requireView();
                    val userIdTextInput: TextInputEditText =
                        thisView.findViewById(R.id.loginIdText); //"kwonkhj01"
                    val carNoTextInput: TextInputEditText =
                        thisView.findViewById(R.id.carNoText);//"70보2495"

                    var _inputId = SaveLogin.getUserId()
                    var _inputCarno = SaveLogin.getCarNo()

                    if (_inputId == null || _inputId.isEmpty()) return;
                    if (_inputCarno == null || _inputCarno.isEmpty()) return;

                    userIdTextInput.setText(_inputId)
                    carNoTextInput.setText(_inputCarno)
                }

            }
        }
    }

    private fun cookieSendResponse(): Callback<JsonObject> {
        return object : Callback<JsonObject> {
            override fun onResponse(call: Call<JsonObject>, response: Response<JsonObject>) {
                if (response.isSuccessful) {
                    println("cookie 성공")

                } else {
                    println("cookie 실패!!")
                }
            }

            override fun onFailure(call: Call<JsonObject>, t: Throwable) {
//16                println("cookie 실패!!")
                println("Request Failed: ${t.message}")
            }
        }
    }

    override fun onResume() {
        super.onResume()
        try {
            val thisView = requireView();
            val userIdTextInput: TextInputEditText =
                thisView.findViewById(R.id.loginIdText); //"kwonkhj01"
            val carNoTextInput: TextInputEditText =
                thisView.findViewById(R.id.carNoText);//"70보2495"

            var _inputId = SaveLogin.getUserId()
            var _inputCarno = SaveLogin.getCarNo()

            if (_inputId == null || _inputId.isEmpty()) return;
            if (_inputCarno == null || _inputCarno.isEmpty()) return;

            userIdTextInput.setText(_inputId)
            carNoTextInput.setText(_inputCarno)
        } catch (e: Exception) {
            //TODO("Not yet implemented")
        }
    }

    private fun moveToHospSearch() {

        try {
            val reqView = requireActivity();
            val bottomNaviView = reqView.findViewById<BottomNavigationView>(R.id.bottom_navigation)
            bottomNaviView.selectedItemId = R.id.hospSearch;
        } catch (e: Exception) {
            //TODO("Not yet implemented")
        }
    }

    private fun currentActionResponse(): Callback<JsonObject> {
        return object : Callback<JsonObject> {
            override fun onResponse(call: Call<JsonObject>, response: Response<JsonObject>) {
                if (response.isSuccessful) {
                    try {
                        val resBody = response.body();
                        val status = resBody?.get("status")?.asString;
                        if (status == "true") {
                            TransferManager.serverState.set(true);

                            AlertDialogUtil.showAlert_OK(
                                context = requireContext(),
                                title = "진행 중인 전송 정보",
                                message = "현재 접속 정보로 진행중인 이송 건이 있습니다.",
                                onPositiveClick = {
                                    moveToHospSearch();
                                }
                            )

                            /*
                            AlertDialogUtil.showAlert(
                                context = requireContext(),
                                title = "진행 중인 전송 정보",
                                message = "현재 접속 정보로 진행중인 이송 건이 있습니다. 취소하시겠습니까?",
                                onPositiveClick = {
                                    TransferManager.cancelTransfer()
                                    moveToHospSearch();
                                },
                                onNegativeClick = {
                                    moveToHospSearch();
                                }
                            )
                            */

                            //시작된 상황
                        }
                        else {
                            TransferManager.serverState.set(false);
                            //시작 아닌 상황
                            moveToHospSearch();
                        }
                    } catch (e: Exception) {
                        println(e.message)
                        moveToHospSearch();
                    }
                } else {
                    moveToHospSearch();
                }
            }

            override fun onFailure(call: Call<JsonObject>, t: Throwable) {
                moveToHospSearch();
            }
        }
    }

}