package com.autotech.we1l.activities

import android.content.Intent
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.widget.AppCompatImageView
import android.view.View
import android.widget.Toast
import com.afollestad.materialdialogs.DialogAction
import com.afollestad.materialdialogs.MaterialDialog
import com.android.volley.VolleyError

import com.autotech.we1l.R
import com.autotech.we1l.app.AppLanguage
import com.autotech.we1l.app.User
import com.autotech.we1l.my_classes.BaseActivity
import com.autotech.we1l.tools.*
import com.autotech.we1l.tools.Language.attr_send_password_rest_email
import com.autotech.we1l.tools.Language.btn_forgot_password
import com.autotech.we1l.tools.Language.btn_log_in
import com.autotech.we1l.tools.Language.btn_send
import com.autotech.we1l.tools.Language.btn_sign_up
import com.autotech.we1l.tools.Language.err_generic_error
import com.autotech.we1l.tools.Language.err_no_internet_connection
import com.autotech.we1l.tools.Language.err_server_connection_error
import com.autotech.we1l.tools.Language.err_some_fields_are_empty
import com.autotech.we1l.tools.Language.err_username_password_incorrect
import com.autotech.we1l.tools.Language.hint_email
import com.autotech.we1l.tools.Language.hint_password
import com.autotech.we1l.tools.Language.toast_password_email_sent
import com.autotech.we1l.volley.IVolleyRequest
import com.autotech.we1l.volley.VolleyRequest
import kotlinx.android.synthetic.main.activity_sign_in.*
import org.json.JSONObject


class SignInActivity : BaseActivity() {

    override fun setupViews() {
    }

    override fun setupClickListeners() {
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_sign_in)

        editTextEmail.hint = AppLanguage.getString(hint_email)
        editTextPassword.hint = AppLanguage.getString(hint_password)

        buttonLogin.text = AppLanguage.getString(btn_log_in)
        textViewSignUp.text = AppLanguage.getString(btn_sign_up)
        textViewForgetPassword.text = AppLanguage.getString(btn_forgot_password)

        buttonLogin.setOnClickListener {
            if (editTextEmail!!.text.toString().trim().isNotEmpty() && editTextPassword!!.text.toString().trim().isNotEmpty()) {
                val inputMap = HashMap<String, String>()
                inputMap[ATTR_SYSTEM_PASSCODE] = SYSTEM_PASSCODE
                inputMap[ATTR_EMAIL] = editTextEmail!!.text.toString().trim()
                inputMap[ATTR_PASSWORD] = editTextPassword!!.text.toString().trim()

                if (!isNetworkAvailable(applicationContext!!)) {
                    Toast.makeText(applicationContext, AppLanguage.getString(err_no_internet_connection), Toast.LENGTH_LONG).show()
                    return@setOnClickListener
                }

                VolleyRequest.getInstance().post(REQUEST_LOG_IN, inputMap, object : IVolleyRequest {

                    override fun onSuccess(response: JSONObject) {
                        when (response.getInt(ATTR_ERROR_CODE)) {
                            CODE_OK -> {
                                User.init(response.getJSONObject(ATTR_DATA).getJSONObject(ATTR_DATA))
                                User.save(applicationContext!!)
                                startActivity(Intent(applicationContext, MainActivity::class.java))
                            }
                            CODE_USER_OR_PASSWORD_INCORRECT -> {
                                Toast.makeText(applicationContext, AppLanguage.getString(err_username_password_incorrect), Toast.LENGTH_LONG).show()
                            }
                        }
                    }

                    override fun onFail(error: VolleyError) {
                        Toast.makeText(applicationContext, AppLanguage.getString(err_server_connection_error), Toast.LENGTH_LONG).show()
                    }
                }).apply { requestsArray.add(this) }

            } else {
                Toast.makeText(applicationContext, AppLanguage.getString(err_some_fields_are_empty), Toast.LENGTH_LONG).show()
            }
        }
        textViewForgetPassword.setOnClickListener {

            val dialog = MaterialDialog.Builder(this)
                    .input(AppLanguage.getString(hint_email), editTextEmail.text.toString().trim(), false) { dialog, input ->
                        dialog.getActionButton(DialogAction.POSITIVE).isEnabled = Tools.isEmailValid(input.toString())
                    }
                    .title(AppLanguage.getString(attr_send_password_rest_email))
                    .alwaysCallInputCallback()
                    .positiveText(AppLanguage.getString(btn_send))
                    .build()

            dialog.show()

            dialog.getActionButton(DialogAction.POSITIVE).isEnabled = Tools.isEmailValid(editTextEmail!!.text.toString().trim())

            dialog.getActionButton(DialogAction.POSITIVE).setOnClickListener {
                val inputMap = HashMap<String, String>()
                inputMap[ATTR_SYSTEM_PASSCODE] = SYSTEM_PASSCODE
                inputMap[ATTR_EMAIL] = dialog.inputEditText!!.text.toString().trim()

                if (!isNetworkAvailable(applicationContext!!)) {
                    Toast.makeText(applicationContext, AppLanguage.getString(err_no_internet_connection), Toast.LENGTH_LONG).show()
                    return@setOnClickListener
                }

                VolleyRequest.getInstance().post(REQUEST_FORGOT_PASSWORD, inputMap, object : IVolleyRequest {
                    override fun onSuccess(response: JSONObject) {
                        when (response.getInt(ATTR_ERROR_CODE)) {
                            CODE_OK -> {
                                dialog.dismiss()
                                runOnUiThread {
                                    Toast.makeText(applicationContext, AppLanguage.getString(toast_password_email_sent), Toast.LENGTH_LONG).show()
                                }
                            }
                            else -> {
                                Toast.makeText(applicationContext, AppLanguage.getString(err_generic_error), Toast.LENGTH_LONG).show()
                            }
                        }
                    }

                    override fun onFail(error: VolleyError) {
                        Toast.makeText(applicationContext, AppLanguage.getString(err_server_connection_error), Toast.LENGTH_LONG).show()
                    }
                }).apply { requestsArray.add(this) }
            }
        }
        textViewSignUp.setOnClickListener { startActivity(Intent(this, SignUpActivity::class.java)) }
        editTextEmail.setOnFocusChangeListener { _, hasFocus ->
            run {
                if (hasFocus) {
                    changeEditText(imageViewEmail, viewEmail)
                }
            }
        }

        editTextPassword.setOnFocusChangeListener { _, hasFocus ->
            run {
                if (hasFocus) {
                    changeEditText(imageViewPassword, viewPassword)
                }
            }
        }
    }

    private fun changeEditText(appCompatImageView: AppCompatImageView, view: View) {
        viewEmail.setBackgroundColor(ContextCompat.getColor(applicationContext, R.color.black_30))
        viewPassword.setBackgroundColor(ContextCompat.getColor(applicationContext, R.color.black_30))

        imageViewEmail.setColorFilter(ContextCompat.getColor(applicationContext, R.color.black_30), android.graphics.PorterDuff.Mode.MULTIPLY)
        imageViewPassword.setColorFilter(ContextCompat.getColor(applicationContext, R.color.black_30), android.graphics.PorterDuff.Mode.MULTIPLY)

        view.setBackgroundColor(ContextCompat.getColor(applicationContext, R.color.colorBlue))
        appCompatImageView.setColorFilter(ContextCompat.getColor(applicationContext, R.color.colorBlue), android.graphics.PorterDuff.Mode.MULTIPLY)
    }
}