/*
 * Copyright (c) 2010-2020 Belledonne Communications SARL.
 *
 * This file is part of linphone-android
 * (see https://www.linphone.org).
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package org.linphone.activities.assistant.fragments

import android.app.Dialog
import android.content.ContentValues.TAG
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.lifecycle.ViewModelProvider
import org.json.JSONObject
import org.linphone.LinphoneApplication
import org.linphone.LinphoneApplication.Companion.coreContext
import org.linphone.R
import org.linphone.activities.GenericFragment
import org.linphone.activities.assistant.AssistantActivity
import org.linphone.activities.assistant.viewmodels.GenericLoginViewModel
import org.linphone.activities.assistant.viewmodels.GenericLoginViewModelFactory
import org.linphone.activities.assistant.viewmodels.SharedAssistantViewModel
import org.linphone.activities.main.viewmodels.DialogViewModel
import org.linphone.activities.navigateToEchoCancellerCalibration
import org.linphone.bluereach.ForgotPassword
import org.linphone.bluereach.SignupActivity
import org.linphone.databinding.AssistantGenericAccountLoginFragmentBinding
import org.linphone.rest.AsyncHttpResponse
import org.linphone.rest.RestApis
import org.linphone.utils.*

class GenericAccountLoginFragment : GenericFragment<AssistantGenericAccountLoginFragmentBinding>(),
    AsyncHttpResponse.AsyncHttpResponseListener {
    private lateinit var sharedViewModel: SharedAssistantViewModel
    private lateinit var viewModel: GenericLoginViewModel
    var sm: SessionManager? = null
    var secondSessionManager: SecondSessionManager? = null
    var keyStatus: Boolean = false

    override fun getLayoutId(): Int = R.layout.assistant_generic_account_login_fragment

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.lifecycleOwner = this

        sharedViewModel = requireActivity().run {
            ViewModelProvider(this).get(SharedAssistantViewModel::class.java)
        }

        viewModel = ViewModelProvider(
            this,
            GenericLoginViewModelFactory(sharedViewModel.getAccountCreator(true))
        ).get(GenericLoginViewModel::class.java)
        binding.viewModel = viewModel
        sm = SessionManager(this.requireContext())

        if (sm!!.getBooleanData(AppStrings.Session.is_login)) {
            binding.alreadyRegisterLl.visibility = View.GONE
            binding.signinForgotPwdTv.visibility = View.GONE
            binding.backIv.visibility = View.VISIBLE
        } else {
            if (sm!!.getBooleanData(AppStrings.Session.is_login)) {
                binding.alreadyRegisterLl.visibility = View.VISIBLE
                binding.signinForgotPwdTv.visibility = View.VISIBLE
                binding.backIv.visibility = View.GONE
            }
        }
        viewModel.leaveAssistantEvent.observe(viewLifecycleOwner, {
            it.consume {
                coreContext.contactsManager.updateLocalContacts()

                if (coreContext.core.isEchoCancellerCalibrationRequired) {
                    LinphoneApplication.corePreferences.firstStart = false
                    navigateToEchoCancellerCalibration()
                } else {
                    LinphoneApplication.corePreferences.firstStart = false
                    requireActivity().finish()
                }
            }
        })

        viewModel.invalidCredentialsEvent.observe(viewLifecycleOwner, {
            it.consume {
                val dialogViewModel =
                    DialogViewModel(getString(R.string.assistant_error_invalid_credentials))
                val dialog: Dialog = DialogUtils.getDialog(requireContext(), dialogViewModel)

                dialogViewModel.showCancelButton {
                    viewModel.removeInvalidProxyConfig()
                    dialog.dismiss()
                }

                dialogViewModel.showDeleteButton({
                    viewModel.continueEvenIfInvalidCredentials()
                    dialog.dismiss()
                }, getString(R.string.assistant_continue_even_if_credentials_invalid))

                dialog.show()
            }
        })

        viewModel.onErrorEvent.observe(viewLifecycleOwner, {
            it.consume { message ->
                (requireActivity() as AssistantActivity).showSnackBar(message)
            }
        })

        binding.login.setOnClickListener {
            Log.e("tag", "signinApi@@@@: ")
            Log.e(TAG, "onViewCreated: " + loginvalidation())
            // signinApi()
        }
        binding.signinForgotPwdTv.setOnClickListener {

            /* redirecting to Forgot password screen*/startActivity(
            Intent(
                activity,
                ForgotPassword::class.java
            )
        )
        }
        binding.signinSignupTv.setOnClickListener {

            startActivity(Intent(this.requireContext(), SignupActivity::class.java))
        }
        binding.backIv.setOnClickListener {
            activity?.finish()
        }
    }

    fun loginvalidation() {
        if (binding.phonenumberEt.text.toString().isEmpty()) {
            AppMethods.alertWithOk2(
                this.requireContext(),
                resources.getString(R.string.enter_number)
            )
        } else if (binding.passwordEt.text.toString().isEmpty()) {
            AppMethods.alertWithOk2(
                this.requireContext(),
                resources.getString(R.string.enter_password)
            )
        } else {
            signinApi()
        }
    }

    fun signinApi() {
        Log.e("tag", "signinApi: ")

        if (AppMethods.isConnectingToInternet(activity)) {
            val response = AsyncHttpResponse(this, true)
            var jo: JSONObject? = null
            try {
                jo = JSONObject()
                jo.put(AppStrings.InputParams.action, RestApis.login)
                val job = JSONObject()
                job.put(
                    AppStrings.InputParams.PhoneNumber,
                    binding.phonenumberEt.text.toString()
                )
                job.put(AppStrings.InputParams.Password, binding.passwordEt.text.toString())
                jo.put(AppStrings.InputParams.params, job)
            } catch (e: Exception) {
                e.printStackTrace()
            }
            response.postJsonAsyncHttp(RestApis.url, RestApis.login, jo)
        } else {
            AppMethods.alertForNoInternet(activity)
        }
    }

    override fun onAsyncHttpResponseGet(response: String?, URL: String?) {
        Log.e("tag", "onAsyncHttpResponseGet:Login " + response)

        try {
            val jo = JSONObject(response)
            val Status = jo.optString(AppStrings.OutputParams.Status)
            val Message = jo.optString(AppStrings.OutputParams.Message)
            if (Status == AppStrings.OutputParams.Success) {
                val userdetails = jo.optString(AppStrings.OutputParams.userdetails)
                val job = JSONObject(userdetails)
                val OTP = job.optString(AppStrings.OutputParams.OTP)
                val FirstName = job.optString(AppStrings.OutputParams.FirstName)
                val LastName = job.optString(AppStrings.OutputParams.LastName)
                val EmailID = job.optString(AppStrings.OutputParams.EmailID)
                val PhoneNumber = job.optString(AppStrings.OutputParams.PhoneNumber)
                val Password = job.optString(AppStrings.OutputParams.Password)
                val userID = job.optString(AppStrings.OutputParams.userID)
                Log.e(
                    TAG,
                    "onAsyncHttpResponseGet@@@: " + job.optString(AppStrings.OutputParams.userID)
                )
                val OtpVerificationStatus =
                    job.optString(AppStrings.OutputParams.OtpVerificationStatus)
                sm!!.setStoreData(
                    AppStrings.Session.login,
                    job.optString(AppStrings.OutputParams.userID)
                )
                sm!!.setStoreData(AppStrings.Session.password, Password)

                Log.e(TAG, "onAsyncHttpResponseGetphone number: " + PhoneNumber)
                Log.e(
                    TAG,
                    "onAsyncHttpResponseGetphone number: " + sm!!.getStoreData(AppStrings.Session.login)
                )

                viewModel.createProxyConfig()
                sm?.setBooleanData(AppStrings.Session.is_login, true)
                secondSessionManager?.username = PhoneNumber
                secondSessionManager?.password = Password
            } else {
                AppMethods.alertWithOk2(activity, Message)
            }
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
        // viewModel.createProxyConfig()
    }
}
