package com.kdanmobile.reader.password

import android.annotation .SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.text.Editable
import android.view.View
import android.view.inputmethod.InputMethodManager
import com.kdanmobile.reader.R
import com.kdanmobile.reader.screen.model.SimpleTextWatcher
import kotlinx.android.synthetic.main.activity_reader_password_dialog.*

class DialogPasswordActivity : AppCompatActivity(), View.OnClickListener {

    private var isIncorrectPassword = false

    @SuppressLint("HandlerLeak")
    private var handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                10 -> (getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).showSoftInput(et_dialogPassword_name, InputMethodManager.RESULT_UNCHANGED_SHOWN)
                20 -> (getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(et_dialogPassword_name.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
            }
        }
    }

    override fun onSaveInstanceState(outState: Bundle?) {
        super.onSaveInstanceState(outState)
        outState?.putBoolean("isIncorrectPassword", isIncorrectPassword)
    }

    override fun onRestoreInstanceState(savedInstanceState: Bundle?) {
        super.onRestoreInstanceState(savedInstanceState)
        updateErrorMessage(savedInstanceState)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setFinishOnTouchOutside(false)
        setContentView(R.layout.activity_reader_password_dialog)
        initView()
        setListener()
    }

    private fun initView() {
        tv_dialogPassword_ok.isEnabled = false
        tv_dialogPassword_ok.setTextColor(ContextCompat.getColor(baseContext, R.color.button_gray))
        handler.sendEmptyMessageDelayed(10, 100)
        updateErrorMessage(intent.extras)
    }

    private fun updateErrorMessage(bundle: Bundle?) {
        if (null != bundle) {
            val value = bundle.getBoolean("isIncorrectPassword", false)
            if (value) {
                layout_dialogPassword_name.error = resources.getString(R.string.reader_dialog_password_error)
                isIncorrectPassword = value
            }
        }
    }

    private fun setListener() {
        tv_dialogPassword_cancel.setOnClickListener(this)
        tv_dialogPassword_ok.setOnClickListener(this)

        et_dialogPassword_name.addTextChangedListener(object : SimpleTextWatcher() {
            override fun afterTextChanged(editable: Editable) {
                super.afterTextChanged(editable)
                val password = editable.toString()
                if (password.isEmpty()) {
                    tv_dialogPassword_ok.isEnabled = false
                    tv_dialogPassword_ok.setTextColor(ContextCompat.getColor(baseContext, R.color.button_gray))
                } else {
                    tv_dialogPassword_ok.isEnabled = true
                    tv_dialogPassword_ok.setTextColor(ContextCompat.getColor(baseContext, R.color.bright_blue))
                }
                if (isIncorrectPassword) {
                    isIncorrectPassword = false
                    layout_dialogPassword_name.error = ""
                }
            }
        })
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.tv_dialogPassword_cancel -> onBackPressed()
            R.id.tv_dialogPassword_ok -> {
                val password = et_dialogPassword_name.text.toString()
                val data = Intent()
                data.putExtra("password", password)
                setResult(RESULT_OK, data)
                finish()
            }
        }
    }

    override fun onResume() {
        super.onResume()
        handler.sendEmptyMessageDelayed(10, 100)
    }

    override fun onBackPressed() {
        val data = Intent()
        data.putExtra("password", "")
        setResult(RESULT_OK, data)
        super.onBackPressed()
    }

    override fun onPause() {
        handler.sendEmptyMessage(20)
        super.onPause()
    }
}
