package com.autotech.we1l.fragments

import android.Manifest
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.InputType
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
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.activities.MainActivity
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.fragments.dialog_fragments.ChangePasswordDialogFragment
import com.autotech.we1l.helpers.InputMap
import com.autotech.we1l.my_classes.BaseFragment
import com.autotech.we1l.my_interfaces.IOnBackPressedListener
import com.autotech.we1l.tools.*
import com.autotech.we1l.tools.Language.attr_mobile
import com.autotech.we1l.tools.Language.attr_name
import com.autotech.we1l.tools.Language.attr_tel
import com.autotech.we1l.tools.Language.btn_change_password
import com.autotech.we1l.tools.Language.dialog_opt_update
import com.autotech.we1l.tools.Language.dialog_opt_upload_from_camera
import com.autotech.we1l.tools.Language.dialog_opt_upload_from_gallery
import com.autotech.we1l.tools.Language.dialog_opt_view_image
import com.autotech.we1l.tools.Language.dialog_update_mobile_number
import com.autotech.we1l.tools.Language.dialog_update_name
import com.autotech.we1l.tools.Language.dialog_update_phone_number
import com.autotech.we1l.tools.Language.err_server_connection_error
import com.autotech.we1l.tools.Language.hint_name
import com.autotech.we1l.tools.Language.prompt_send_photos
import com.autotech.we1l.volley.IVolleyRequest
import com.autotech.we1l.volley.VolleyRequest
import kotlinx.android.synthetic.main.fragment_profile.*
import kotlinx.android.synthetic.main.include_not_logged_in.*
import org.json.JSONObject
import pub.devrel.easypermissions.EasyPermissions

class ProfileFragment : BaseFragment(), IOnBackPressedListener {

    private val perms = arrayOf(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)

    private val uploadFileManager = UploadFileManager_Fragment()

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        rootView = inflater.inflate(R.layout.fragment_profile, container, false)
        return rootView
    }

    override fun setupViews() {

        if (!User.isValid()) {
            not_logged_in_prompt.visibility = View.VISIBLE
            main_layout.visibility = View.GONE

            sign_in_or_sign_up.setOnClickListener {
                val sharedPreferences = context!!.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
                sharedPreferences.edit().putBoolean(ATTR_IS_UNREGISTERED, false).apply()
                launchFirstActivity(activity!!)
            }
            return
        }

        PicassoUtils.getImage(User.instance!!.imageUrl, context!!, profile_image)

        name.text = User.instance!!.fullName
        tel.text = User.instance!!.phone
        mobile.text = User.instance!!.mobile

    }

    override fun setupClickListeners() {
        profile_image.setOnClickListener {
            MaterialDialog.Builder(context!!)
                    .items(AppLanguage.getString(dialog_opt_view_image), AppLanguage.getString(dialog_opt_upload_from_camera), AppLanguage.getString(dialog_opt_upload_from_gallery))
                    .itemsCallback { _, _, position, _ ->
                        when (position) {
                            0 -> {

                            }
                            1 -> {
                                if (EasyPermissions.hasPermissions(this.context!!, *perms))
                                    uploadFileManager.launchCamera(this)
                                else
                                    EasyPermissions.requestPermissions(this,
                                            AppLanguage.getString(prompt_send_photos), CAMERA_STORAGE_REQUEST, *perms)
                            }
                            2 -> {
                                if (EasyPermissions.hasPermissions(this.context!!, *perms))
                                    uploadFileManager.launchGallery(this)
                                else
                                    EasyPermissions.requestPermissions(this,
                                            AppLanguage.getString(prompt_send_photos), GALLERY_STORAGE_REQUEST, *perms)
                            }
                        }
                    }
                    .show()
        }

        edit_name.setOnClickListener {
            var newName = ""
            val dialog = MaterialDialog.Builder(context!!)
                    .title(AppLanguage.getString(dialog_update_name))
                    .input(AppLanguage.getString(hint_name), "", false) { dialog, input ->
                        dialog.getActionButton(DialogAction.POSITIVE).isEnabled = input.trim().isNotEmpty()
                                && User.instance!!.fullName != input.toString().trim()
                        newName = input.trim().toString()
                    }
                    .alwaysCallInputCallback()
                    .positiveText(AppLanguage.getString(dialog_opt_update))
                    .show()
            dialog.getActionButton(DialogAction.POSITIVE).setOnClickListener {
                VolleyRequest.getInstance()
                        .post(REQUEST_CHANGE_INFO, InputMap().apply {
                            put(ATTR_SYSTEM_PASSCODE, SYSTEM_PASSCODE)
                            put(ATTR_CUSTOMER, User.instance!!.id.toString())
                            put(ATTR_FULLNAME, newName)
                        }, object : IVolleyRequest {

                            override fun onSuccess(response: JSONObject?) {
                                when (response!!.getInt(ATTR_ERROR_CODE)) {
                                    CODE_OK -> {
                                        name.text = newName
                                        User.load(context!!)
                                        User.instance?.fullName = newName
                                        User.save(context!!)
                                        (activity as MainActivity).getUserPoints()
                                        dialog.dismiss()
                                    }
                                }
                            }

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

        edit_tel.setOnClickListener {
            var newPhoneNumber = ""
            val dialog = MaterialDialog.Builder(context!!)
                    .title(AppLanguage.getString(dialog_update_phone_number))
                    .input(AppLanguage.getString(hint_name), "", false) { dialog, input ->
                        dialog.getActionButton(DialogAction.POSITIVE).isEnabled = input.trim().isNotEmpty()
                                && User.instance!!.phone != input.toString().trim()
                        newPhoneNumber = input.trim().toString()
                    }
                    .inputType(InputType.TYPE_CLASS_NUMBER)
                    .alwaysCallInputCallback()
                    .positiveText(AppLanguage.getString(dialog_opt_update))
                    .show()
            dialog.getActionButton(DialogAction.POSITIVE).setOnClickListener {
                VolleyRequest.getInstance()
                        .post(REQUEST_CHANGE_INFO, InputMap().apply {
                            put(ATTR_SYSTEM_PASSCODE, SYSTEM_PASSCODE)
                            put(ATTR_CUSTOMER, User.instance!!.id.toString())
                            put(ATTR_TEL, newPhoneNumber)
                        }, object : IVolleyRequest {

                            override fun onSuccess(response: JSONObject?) {
                                when (response!!.getInt(ATTR_ERROR_CODE)) {
                                    CODE_OK -> {
                                        tel.text = newPhoneNumber
                                        dialog.dismiss()
                                    }
                                }
                            }

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

        edit_mobile.setOnClickListener {
            var newMobileNumber = ""
            val dialog = MaterialDialog.Builder(context!!)
                    .title(AppLanguage.getString(dialog_update_mobile_number))
                    .input(AppLanguage.getString(hint_name), "", false) { dialog, input ->
                        dialog.getActionButton(DialogAction.POSITIVE).isEnabled = input.trim().isNotEmpty()
                                && User.instance!!.mobile != input.toString().trim()
                        newMobileNumber = input.trim().toString()
                    }
                    .inputType(InputType.TYPE_CLASS_NUMBER)
                    .alwaysCallInputCallback()
                    .positiveText(AppLanguage.getString(dialog_opt_update))
                    .show()
            dialog.getActionButton(DialogAction.POSITIVE).setOnClickListener {
                VolleyRequest.getInstance()
                        .post(REQUEST_CHANGE_INFO, InputMap().apply {
                            put(ATTR_SYSTEM_PASSCODE, SYSTEM_PASSCODE)
                            put(ATTR_CUSTOMER, User.instance!!.id.toString())
                            put(ATTR_MOBILE, newMobileNumber)
                        }, object : IVolleyRequest {

                            override fun onSuccess(response: JSONObject?) {
                                when (response!!.getInt(ATTR_ERROR_CODE)) {
                                    CODE_OK -> {
                                        mobile.text = newMobileNumber
                                        dialog.dismiss()
                                    }
                                }
                            }

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

        change_password.setOnClickListener {
            val changePasswordDialogFragment = ChangePasswordDialogFragment()
            changePasswordDialogFragment.show(childFragmentManager, "ChangePasswordDialogFragment")
        }
    }

    override fun setupLanguages() {
        super.setupLanguages()
        name_title.text = AppLanguage.getString(attr_name)
        tel_title.text = AppLanguage.getString(attr_tel)
        mobile_title.text = AppLanguage.getString(attr_mobile)

        change_password.text = AppLanguage.getString(btn_change_password)
    }

    override fun onBackPressed(): Boolean {
        return false
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        uploadFileManager.onResult(requestCode, resultCode, this, data, 20) { sentFile, _, _ ->
            UploadRequest.getInstance()
                    .uploadFile(REQUEST_CHANGE_IMAGE, InputMap().apply {
                        put(ATTR_SYSTEM_PASSCODE, SYSTEM_PASSCODE)
                        put(ATTR_CUSTOMER, User.instance!!.id.toString())
                        put(ATTR_IMAGE, sentFile.path)
                    }, object : UploadRequest.OnUploadListener {

                        override fun onSuccess(response: JSONObject?) {
                            if (!isResumed) return
                            when (response!!.getInt(ATTR_ERROR_CODE)) {
                                CODE_OK -> {
                                    activity!!.runOnUiThread {
                                        val imageUrl = response.getJSONObject(ATTR_DATA).getJSONObject(ATTR_DATA).getString(ATTR_IMAGE_URL)
                                        PicassoUtils.invalidate(User.instance!!.imageUrl)
                                        User.instance!!.imageUrl = imageUrl
                                        User.save(context!!)
                                        PicassoUtils.getImage(imageUrl, context!!, profile_image)
                                        (activity as MainActivity).getUserPoints()
                                    }
                                }
                            }
                        }

                        override fun onFailed(response: JSONObject?) {

                        }

                    }, ATTR_IMAGE)
        }
    }

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

    override fun crucialRequests() {
    }


}