package com.autotech.we1l.activities

import android.content.Intent
import android.graphics.PorterDuff
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.view.View
import android.widget.EditText
import android.widget.Toast
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.file_upload_utils.UploadFileManager_Activity
import com.autotech.we1l.file_upload_utils.UploadFileManager_Fragment
import com.autotech.we1l.file_upload_utils.UploadRequest
import com.autotech.we1l.helpers.AnimatorUtils
import com.autotech.we1l.my_classes.BaseActivity
import com.autotech.we1l.tools.*
import com.autotech.we1l.tools.Language.btn_sign_up
import com.autotech.we1l.tools.Language.hint_confirm_password
import com.autotech.we1l.tools.Language.hint_email
import com.autotech.we1l.tools.Language.hint_full_name
import com.autotech.we1l.tools.Language.hint_insurance_name
import com.autotech.we1l.tools.Language.hint_insurance_number
import com.autotech.we1l.tools.Language.hint_mobile
import com.autotech.we1l.tools.Language.hint_password
import com.autotech.we1l.tools.Language.hint_phone_optional
import com.autotech.we1l.tools.Language.hint_zip_code
import com.autotech.we1l.volley.IVolleyRequest
import com.autotech.we1l.volley.VolleyRequest
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.activity_sign_up.*
import org.json.JSONObject
import pub.devrel.easypermissions.EasyPermissions


class SignUpActivity : BaseActivity(), View.OnFocusChangeListener {

    private val uploadFileManager = UploadFileManager_Activity()

    override fun setupViews() {
    }

    override fun setupClickListeners() {
    }

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

        setContentView(R.layout.activity_sign_up)

        editTextFullName.hint = AppLanguage.getString(hint_full_name)
        editTextEmail.hint = AppLanguage.getString(hint_email)
        editTextPassword.hint = AppLanguage.getString(hint_password)
        editTextPasswordConfirm.hint = AppLanguage.getString(hint_confirm_password)
        editTextPhone.hint = AppLanguage.getString(hint_phone_optional)
        editTextMobile.hint = AppLanguage.getString(hint_mobile)
        editTextZipCode.hint = AppLanguage.getString(hint_zip_code)
        editTextInsuranceName.hint = AppLanguage.getString(hint_insurance_name)
        editTextInsuranceNumber.hint = AppLanguage.getString(hint_insurance_number)
        buttonSignUp.text = AppLanguage.getString(btn_sign_up)

        editTextFullName.onFocusChangeListener = this
        editTextEmail.onFocusChangeListener = this
        editTextPassword.onFocusChangeListener = this
        editTextPasswordConfirm.onFocusChangeListener = this
        editTextPhone.onFocusChangeListener = this
        editTextMobile.onFocusChangeListener = this
        editTextZipCode.onFocusChangeListener = this
        editTextInsuranceName.onFocusChangeListener = this
        editTextInsuranceNumber.onFocusChangeListener = this

        profile_image_layout.setOnClickListener {
            uploadFileManager.launchDialog(this, true)
        }

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

            if (editTextFullName.text.toString().trim().isEmpty()
                    && editTextEmail.text.toString().trim().isEmpty()
                    && editTextPassword.text.toString().trim().isEmpty()
                    && editTextPasswordConfirm.text.toString().trim().isEmpty()
                    && editTextMobile.text.toString().trim().isEmpty()) {

                Toast.makeText(applicationContext, AppLanguage.getString(Language.err_some_fields_are_empty), Toast.LENGTH_LONG).show()

                return@setOnClickListener
            }

            if (editTextMobile.text.toString() == editTextPhone.text.toString()) {
                Toast.makeText(applicationContext, AppLanguage.getString(Language.err_no_mobile), Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }

            if (!checkEmailAndPassword()) return@setOnClickListener

            if (!editTextMobile.text.toString().trim().matches(Regex("^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})\$"))) {
                Toast.makeText(applicationContext, AppLanguage.getString(Language.err_no_mobile), Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }

            if (editTextPassword.text.toString().trim() != editTextPasswordConfirm.text.toString().trim()) {
                Toast.makeText(applicationContext, AppLanguage.getString(Language.err_passwords_dont_match), Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }

            val inputMap = HashMap<String, String>()

            inputMap[ATTR_SYSTEM_PASSCODE] = SYSTEM_PASSCODE
            inputMap[ATTR_FULLNAME] = editTextFullName.text.toString().trim()
            inputMap[ATTR_EMAIL] = editTextEmail.text.toString().trim()
            inputMap[ATTR_PASSWORD] = editTextPassword.text.toString().trim()
            inputMap[ATTR_ZIPCODE] = editTextZipCode.text.toString().trim()
            inputMap[ATTR_PHONE] = editTextPhone.text.toString().trim()
            inputMap[ATTR_MOBILE] = editTextMobile.text.toString().trim()
            inputMap[ATTR_INSURANCE_NAME] = editTextInsuranceName.text.toString().trim()
            inputMap[ATTR_INSURANCE_NUMBER] = editTextInsuranceNumber.text.toString().trim()
            inputMap[ATTR_IS_ANDROID] = "1"
            inputMap[ATTR_TOKEN] = "5487"

            if (uploadFileManager.sentFile == null) {
                loading()
                inputMap[ATTR_IMAGE] = ""
                VolleyRequest.getInstance()
                        .post(REQUEST_SIGN_UP, inputMap, object : IVolleyRequest {

                            override fun onSuccess(response: JSONObject) {
                                done()
                                when (response.getInt(ATTR_ERROR_CODE)) {
                                    CODE_OK -> {
                                        Toast.makeText(applicationContext, AppLanguage.getString(Language.toast_wait_for_confirmation_email),
                                                Toast.LENGTH_LONG).show()
                                        clearFields()
                                        finish()
                                    }
                                    CODE_MISSING_DATA -> {
                                        Toast.makeText(applicationContext, AppLanguage.getString(Language.err_empty_fields),
                                                Toast.LENGTH_LONG).show()
                                    }
                                    CODE_EMAIL_ALREADY_EXISTS -> {
                                        Toast.makeText(applicationContext, AppLanguage.getString(Language.err_email_already_exists),
                                                Toast.LENGTH_LONG).show()
                                    }
                                }
                            }

                            override fun onFail(errorListener: VolleyError) {
                                done()
                                Toast.makeText(applicationContext, AppLanguage.getString(Language.err_server_connection_error),
                                        Toast.LENGTH_LONG).show()
                            }
                        }).apply { requestsArray.add(this) }
            } else {
                loading()
                UploadRequest.getInstance().uploadFile(REQUEST_SIGN_UP, inputMap, object : UploadRequest.OnUploadListener {

                    override fun onSuccess(response: JSONObject) {
                        done()
                        when (response.getInt(ATTR_ERROR_CODE)) {
                            CODE_OK -> {
                                Toast.makeText(applicationContext, AppLanguage.getString(Language.toast_wait_for_confirmation_email), Toast.LENGTH_LONG).show()
                            }
                        }
                    }

                    override fun onFailed(response: JSONObject?) {
                        done()
                    }
                }, ATTR_IMAGE)
            }

        }
    }

    override fun setupLanguages() {
        super.setupLanguages()
        editTextFullName.hint = AppLanguage.getString(hint_full_name)
        editTextEmail.hint = AppLanguage.getString(hint_email)
        editTextPassword.hint = AppLanguage.getString(hint_password)
        editTextPasswordConfirm.hint = AppLanguage.getString(hint_confirm_password)
        editTextZipCode.hint = AppLanguage.getString(hint_zip_code)
        editTextPhone.hint = AppLanguage.getString(hint_phone_optional)
        editTextMobile.hint = AppLanguage.getString(hint_mobile)
        editTextInsuranceName.hint = AppLanguage.getString(hint_insurance_name)
        editTextInsuranceNumber.hint = AppLanguage.getString(hint_insurance_number)
        buttonSignUp.text = AppLanguage.getString(btn_sign_up)
        loading_title.text = AppLanguage.getString(Language.dialog_loading)
    }

    override fun onFocusChange(view: View?, hasFocus: Boolean) {

        if (!hasFocus)
            changeColor(R.color.black_30,
                    editTextFullName,
                    editTextEmail,
                    editTextPassword,
                    editTextPasswordConfirm,
                    editTextPhone,
                    editTextMobile,
                    editTextZipCode,
                    editTextInsuranceName,
                    editTextInsuranceNumber)

        if (hasFocus) changeColor(R.color.colorBlue, view as EditText)
    }

    private fun changeColor(color: Int, vararg editTexts: EditText) {
        for (editText in editTexts)
            if (User.getUserLanguage(this) == "ar")
                editText.compoundDrawables[2].setColorFilter(ContextCompat.getColor(applicationContext, color), PorterDuff.Mode.SRC_IN)
            else editText.compoundDrawables[0].setColorFilter(ContextCompat.getColor(applicationContext, color), PorterDuff.Mode.SRC_IN)
    }

    private fun checkEmailAndPassword(): Boolean {
        var result = true
        var errors = ""

        if (!Tools.isEmailValid(editTextEmail!!.text.toString().trim())) {
            errors += "${AppLanguage.getString(Language.err_email_address_invalid)}\n"
            result = false
        }

        val password = editTextPassword!!.text.toString().trim()
        if (password.length < 8) {
            result = false
            errors += AppLanguage.getString(Language.err_password_too_short)
        }

        if (!password.matches(Regex("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#\$%^&+=])(?=\\S+\$).{8,}\$"))) {
            result = false
            errors += AppLanguage.getString(Language.err_password_too_short)
        }

        if (!result) {
            Toast.makeText(applicationContext, errors, Toast.LENGTH_LONG).show()
        }
        return result
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        uploadFileManager.onResult(requestCode, resultCode, this, data) { file, bitmap, isFile ->
            Picasso.get()
                    .load(file)
                    .centerCrop().fit()
                    .into(profile_image)
            profile_image.setPadding(0, 0, 0, 0)
            profile_image.clearColorFilter()
        }
    }

    private fun loading() {
        main_layout.alpha = 0.5f
        main_layout.isEnabled = false
        AnimatorUtils.show(loading_layout)
    }

    private fun done() {
        main_layout.alpha = 1f
        main_layout.isEnabled = true
        AnimatorUtils.hide(loading_layout)
    }

    private fun clearFields() {
        editTextFullName.setText("")
        editTextEmail.setText("")
        editTextPassword.setText("")
        editTextPasswordConfirm.setText("")
        editTextZipCode.setText("")
        editTextPhone.setText("")
        editTextMobile.setText("")
        editTextInsuranceName.setText("")
        editTextInsuranceNumber.setText("")
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (EasyPermissions.hasPermissions(applicationContext, uploadFileManager.perms[0], uploadFileManager.perms[1])) {
            when (requestCode) {
                UploadFileManager_Fragment.CAMERA_STORAGE_REQUEST -> uploadFileManager.launchCamera(this)
                UploadFileManager_Fragment.GALLERY_STORAGE_REQUEST -> uploadFileManager.launchGallery(this)
            }
        }
    }
}
