package com.sambath.sbc.screen.setting

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import com.google.android.material.button.MaterialButton
import com.google.android.material.textfield.TextInputLayout
import com.mazenrashed.printooth.Printooth
import com.mazenrashed.printooth.ui.ScanningActivity
import com.sambath.sbc.R
import com.sambath.sbc.app.App
import com.sambath.sbc.app.ShareActivity
import com.sambath.sbc.base.BaseFragment
import com.sambath.sbc.extension.btnClick
import com.sambath.sbc.remote.ChangePwd
import com.sambath.sbc.remote.User
import com.sambath.sbc.screen.login.LoginActivity
import com.sambath.sbc.util.Const
import com.sambath.sbc.util.ModelPreferencesManager
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: MaterialButton
    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)
        user = ModelPreferencesManager.get<User>(Const.USER_KEY)!!
        (requireActivity() as ShareActivity).apply {
//            betTouch = MediaPlayer.create(this, R.raw.bettouch)
//            user = userShare
        }
    }

    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
            layCfStatus.isVisible = false
            btnClose = view.findViewById<MaterialButton>(R.id.btn_close)
            btnClose.setOnClickListener {
//                if (!sharePref.getIsMute()) betTouch.start()
                it.btnClick().subscribe {
                    onBackPressed()
                }
            }
        }
        val tilCurrentPwd = view.findViewById<TextInputLayout>(R.id.til_new_pwd)
        val tilNewPwd = 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 = ""
                tilCurrentPwd.error = null
                tilCurrentPwd.isErrorEnabled = false
                tilNewPwd.error = null
                tilNewPwd.isErrorEnabled = false
                val currentPwd = et_current_pwd.text
                val newPwd = et_new_pwd.text
                if (currentPwd.isNullOrEmpty()) {
                    tilCurrentPwd.error = getString(R.string.err_not_empty)
                    tilCurrentPwd.requestFocus()
                    tv_error.text = getString(R.string.err_not_empty)
                    return@subscribe
                }
                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 (currentPwd.toString() == newPwd.toString()) {
                    tilCurrentPwd.error = getString(R.string.err_wrong_pwd)
                    tilNewPwd.error = getString(R.string.err_wrong_pwd)
                    tv_error.text = getString(R.string.err_wrong_pwd)
                    return@subscribe
                }
                settingViewModel.updatePassword(
                    ChangePwd(currentPwd.toString().trim(), newPwd.toString().trim())
                )
            }
        }

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