package com.khmer9.yuki.screen.setting

import android.app.Activity
import android.content.Intent
import android.media.MediaPlayer
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import com.google.android.material.textfield.TextInputLayout
import com.khmer9.yuki.R
import com.khmer9.yuki.app.App
import com.khmer9.yuki.app.ShareActivity
import com.khmer9.yuki.base.BaseFragment
import com.khmer9.yuki.extension.btnClick
import com.khmer9.yuki.remote.User
import com.khmer9.yuki.screen.login.LoginActivity
import com.mazenrashed.printooth.Printooth
import com.mazenrashed.printooth.ui.ScanningActivity
import kotlinx.android.synthetic.main.fragment_setting.*

/**
 * A simple [Fragment] subclass as the second destination in the navigation.
 */
class SettingFragment : BaseFragment(R.layout.fragment_setting) {
    private lateinit var btnClose: ImageView
    private lateinit var user: User
    private lateinit var betTouch: MediaPlayer
    private val sharePref = App.injectPrefHelper()
    private lateinit var settingViewModel: SettingViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        settingViewModel = SettingViewModel(App.injectApiService(), App.injectPrefHelper())
        super.onCreate(savedInstanceState)
        (requireActivity() as ShareActivity).apply {
            betTouch = MediaPlayer.create(this, R.raw.bettouch)
            //user = userShare
            user = loginData.user!!
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        settingViewModel.state.observe(viewLifecycleOwner, androidx.lifecycle.Observer {
            getResult(it)
        })

        (requireActivity() as? ShareActivity)?.apply {
            groupToolbarIcons.isVisible = false
            btnClose = view.findViewById<ImageView>(R.id.btn_close)
            btnClose.setOnClickListener {
                if (!sharePref.getIsMute()) betTouch.start()
                it.btnClick().subscribe {
                    onBackPressed()
                }
            }
        }

        val tilNewPwd = view.findViewById<TextInputLayout>(R.id.til_new_pwd)
        val tilConfirmPwd = view.findViewById<TextInputLayout>(R.id.til_confirm_pwd)
        sw_print.isChecked = sharePref.getIsAutoPrint()

        val hasPair = Printooth.hasPairedPrinter()

        if (hasPair) {
            v_print.setImageViewIcon(R.drawable.blue_text_dc)
            val pair = Printooth.getPairedPrinter()
            text_connect.text = pair?.name
        }

        v_save.setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {
                tv_error.text = ""
                tilNewPwd.error = null
                tilNewPwd.isErrorEnabled = false
                tilConfirmPwd.error = null
                tilConfirmPwd.isErrorEnabled = false
                val newPwd = et_new_pwd.text
                val confirmPwd = et_confirm_pwd.text
                if (newPwd.isNullOrEmpty()) {
                    tilNewPwd.error = getString(R.string.err_not_empty)
                    tilNewPwd.requestFocus()
                    tv_error.text = getString(R.string.err_not_empty)
                    return@subscribe
                }

                if (confirmPwd.isNullOrEmpty()) {
                    tilConfirmPwd.error = getString(R.string.err_not_empty)
                    tilConfirmPwd.requestFocus()
                    tv_error.text = getString(R.string.err_not_empty)
                    return@subscribe
                }

                if (newPwd.toString() != confirmPwd.toString()) {
                    tilNewPwd.error = getString(R.string.err_wrong_pwd)
                    tilConfirmPwd.error = getString(R.string.err_wrong_pwd)
                    tv_error.text = getString(R.string.err_wrong_pwd)
                    return@subscribe
                }

                settingViewModel.updatePassword(oldPassword = newPwd.toString(), newPassword = confirmPwd.toString())

            }


        }

        sw_print.setOnCheckedChangeListener { _, isChecked ->
            if (!sharePref.getIsMute()) betTouch.start()
            sharePref.setIsAutoPrint(isChecked)
        }
        sw_bluetooth.setOnCheckedChangeListener { _, _ ->
            if (!sharePref.getIsMute()) betTouch.start()

        }
        v_print.setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {
                if (hasPair) {
                    Printooth.removeCurrentPrinter()
                    v_print.setImageViewIcon(R.drawable.blue_text_connect)
                    text_connect.text = ""

                } else startActivityForResult(Intent(requireActivity(), ScanningActivity::class.java), ScanningActivity.SCANNING_FOR_PRINTER)

            }
        }
        v_logout.setOnClickListener {
            if (!sharePref.getIsMute()) betTouch.start()
            it.btnClick().subscribe {
                sharePref.logout()

                val intent = Intent(requireContext(), LoginActivity::class.java)
                startActivity(intent)
                requireActivity().finishAffinity()

            }
        }

    }

    private fun getResult(state: UpdatePwdViewState) {

        // if (state.isProgress){
        // Toast.makeText(requireContext(), "Loading", Toast.LENGTH_LONG).show()

        //}
        if (state.isUpdateSuccess) {
            //Toast.makeText(requireContext(), "Update Sucess", Toast.LENGTH_LONG).show()
            val intent = Intent(requireContext(), LoginActivity::class.java)
            startActivity(intent)
            requireActivity().finishAffinity()

        }
        if (state.error != null) {
            //Toast.makeText(requireContext(), "Error", Toast.LENGTH_LONG).show()
            tv_error.text = state.error


        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == ScanningActivity.SCANNING_FOR_PRINTER && resultCode == Activity.RESULT_OK) {

            val pair = Printooth.getPairedPrinter()
            v_print.setImageViewIcon(R.drawable.blue_text_dc)
            text_connect.text = pair?.name


            //Printooth.removeCurrentPrinter()
//https://github.com/mazenrashed/Printooth

        }
        //Printer is ready now
    }
}
