package com.autotech.we1l.fragments

import android.Manifest
import android.annotation.SuppressLint
import android.app.DatePickerDialog
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.afollestad.materialdialogs.MaterialDialog
import com.autotech.we1l.R
import com.autotech.we1l.app.AppLanguage
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.InputMap
import com.autotech.we1l.items.AdDimensions
import com.autotech.we1l.my_classes.BaseFragment
import com.autotech.we1l.my_classes.BaseList
import com.autotech.we1l.tools.*
import com.autotech.we1l.tools.Language.attr_err_image_size
import com.autotech.we1l.tools.Language.attr_size
import com.autotech.we1l.tools.Language.attr_start_at
import com.autotech.we1l.tools.Language.attr_type
import com.autotech.we1l.tools.Language.btn_request_ad
import com.autotech.we1l.tools.Language.dialog_opt_request_another
import com.autotech.we1l.tools.Language.err_email_address_invalid
import com.autotech.we1l.tools.Language.err_no_email
import com.autotech.we1l.tools.Language.err_no_mobile
import com.autotech.we1l.tools.Language.err_no_name
import com.autotech.we1l.tools.Language.err_no_number_of_days
import com.autotech.we1l.tools.Language.err_no_selected_photo
import com.autotech.we1l.tools.Language.err_no_start_date
import com.autotech.we1l.tools.Language.err_no_tel
import com.autotech.we1l.tools.Language.err_no_title
import com.autotech.we1l.tools.Language.err_number_of_days_too_large
import com.autotech.we1l.tools.Language.hint_content
import com.autotech.we1l.tools.Language.hint_email
import com.autotech.we1l.tools.Language.hint_mobile
import com.autotech.we1l.tools.Language.hint_name
import com.autotech.we1l.tools.Language.hint_number_of_days
import com.autotech.we1l.tools.Language.hint_size
import com.autotech.we1l.tools.Language.hint_tel
import com.autotech.we1l.tools.Language.hint_title
import com.autotech.we1l.tools.Language.hint_type
import com.autotech.we1l.tools.Language.toast_done
import com.autotech.we1l.tools.Language.toast_success_ad_request_sent
import com.autotech.we1l.tools.Language.txt_v_select_date
import com.autotech.we1l.tools.Language.txt_v_select_photo
import kotlinx.android.synthetic.main.fragment_request_ad.*
import org.json.JSONObject
import pub.devrel.easypermissions.EasyPermissions
import java.util.*

class RequestAdFragment : BaseFragment() {

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

    private val uploadFileManager = UploadFileManager_Fragment()
    private val adsDimens = BaseList<AdDimensions>()
    private val adsTypes = arrayListOf("Gold", "Silver", "Bronze")

    // Vars
    private var selectedPhoto: Bitmap? = null
    private var startAtDate: Calendar? = null

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

    override fun setupViews() {
        adsDimens.apply {
            add(AdDimensions("Full", 1800, 600))
            add(AdDimensions("Mid", 900, 450))
            add(AdDimensions("Small", 600, 600))
        }

        type_spinner.setItems(adsTypes)
        size_spinner.setItems(adsDimens.names)

    }

    @SuppressLint("SetTextI18n")
    override fun setupClickListeners() {
        select_photo.setOnClickListener {
            uploadFileManager.launchDialog(this, true)
        }

        select_start_date.setOnClickListener {
            val currCalendar = if (startAtDate != null) startAtDate!! else Calendar.getInstance()

            val dialog = DatePickerDialog(context!!, DatePickerDialog.OnDateSetListener { _, year, month, dayOfMonth ->
                start_at_date.text = "$year-${month + 1}-$dayOfMonth"
                startAtDate = Calendar.getInstance().apply {
                    set(Calendar.YEAR, year)
                    set(Calendar.MONTH, month)
                    set(Calendar.DAY_OF_MONTH, dayOfMonth)
                }
            }, currCalendar[Calendar.YEAR], currCalendar[Calendar.MONTH], currCalendar[Calendar.DAY_OF_MONTH])

            dialog.datePicker.minDate = Calendar.getInstance().timeInMillis

            dialog.show()
        }

        request_ad.setOnClickListener {
            when {
                selectedPhoto == null -> {
                    Toast.makeText(context, AppLanguage.getString(err_no_selected_photo), Toast.LENGTH_LONG).show()
                    return@setOnClickListener
                }
                name.editText!!.text.toString().trim().isEmpty() -> {
                    Toast.makeText(context, AppLanguage.getString(err_no_name), Toast.LENGTH_LONG).show()
                    return@setOnClickListener
                }
                email.editText!!.text.toString().trim().isEmpty() -> {
                    Toast.makeText(context, AppLanguage.getString(err_no_email), Toast.LENGTH_LONG).show()
                    return@setOnClickListener
                }
                !Tools.isEmailValid(email.editText!!.text.toString().trim()) -> {
                    Toast.makeText(context, AppLanguage.getString(err_email_address_invalid), Toast.LENGTH_LONG).show()
                    return@setOnClickListener
                }
                tel.editText!!.text.toString().trim().isEmpty() -> {
                    Toast.makeText(context, AppLanguage.getString(err_no_tel), Toast.LENGTH_LONG).show()
                    return@setOnClickListener
                }
                mobile.editText!!.text.toString().trim().isEmpty() -> {
                    Toast.makeText(context, AppLanguage.getString(err_no_mobile), Toast.LENGTH_LONG).show()
                    return@setOnClickListener
                }
                title.editText!!.text.toString().trim().isEmpty() -> {
                    Toast.makeText(context, AppLanguage.getString(err_no_title), Toast.LENGTH_LONG).show()
                    return@setOnClickListener
                }
                startAtDate == null -> {
                    Toast.makeText(context, AppLanguage.getString(err_no_start_date), Toast.LENGTH_LONG).show()
                    return@setOnClickListener
                }
                number_of_days.editText!!.text.toString().trim().isEmpty() -> {
                    Toast.makeText(context, AppLanguage.getString(err_no_number_of_days), Toast.LENGTH_LONG).show()
                    return@setOnClickListener
                }
                number_of_days.editText!!.text.toString().trim().toInt() > 60 -> {
                    Toast.makeText(context, AppLanguage.getString(err_number_of_days_too_large), Toast.LENGTH_LONG).show()
                    return@setOnClickListener
                }
            }
            UploadRequest.getInstance()
                    .uploadFile(REQUEST_ADD_AD, InputMap().apply {
                        put(ATTR_SYSTEM_PASSCODE, SYSTEM_PASSCODE)
                        put(ATTR_NAME, name.editText!!.text.toString().trim())
                        put(ATTR_EMAIL, email.editText!!.text.toString().trim())
                        put(ATTR_TEL, tel.editText!!.text.toString().trim())
                        put(ATTR_MOBILE, mobile.editText!!.text.toString().trim())
                        put(ATTR_TYPE, type_spinner.getItems<String>()[type_spinner.selectedIndex])
                        put(ATTR_PIXEL_SIZE, adsDimens[size_spinner.selectedIndex].size)
                        put(ATTR_TITLE, title.editText!!.text.toString().trim())
                        put(ATTR_START_AT, startAtDate!!.timeInMillis.toString())
                        put(ATTR_NUMBER_OF_DAYS, number_of_days.editText!!.text.toString().trim())
                        put(ATTR_CONTENT, short_bio.editText!!.text.toString().trim())
                        put(ATTR_IMAGE_URL, uploadFileManager.sentFile.absolutePath)

                    }, object : UploadRequest.OnUploadListener {
                        override fun onSuccess(response: JSONObject?) {
                            when (response!!.getInt(ATTR_ERROR_CODE)) {
                                CODE_OK -> {
                                    activity?.runOnUiThread {
                                        MaterialDialog.Builder(context!!)
                                                .content(AppLanguage.getString(toast_success_ad_request_sent))
                                                .positiveText(AppLanguage.getString(toast_done))
                                                .onPositive { _, _ ->
                                                    activity?.finish()
                                                }
                                                .neutralText(AppLanguage.getString(dialog_opt_request_another))
                                                .onNeutral { _, _ ->
                                                    reset()
                                                }.show()
                                    }

                                }
                            }
                        }

                        override fun onFailed(response: JSONObject?) {

                        }
                    }, ATTR_IMAGE_URL)

        }
    }

    override fun setupLanguages() {
        super.setupLanguages()
        select_photo_title.text = AppLanguage.getString(txt_v_select_photo)
        name.hint = AppLanguage.getString(hint_name)
        email.hint = AppLanguage.getString(hint_email)
        tel.hint = AppLanguage.getString(hint_tel)
        mobile.hint = AppLanguage.getString(hint_mobile)

        type_title.hint = AppLanguage.getString(attr_type)
        type_spinner.hint = AppLanguage.getString(hint_type)

        size_title.hint = AppLanguage.getString(attr_size)
        size_spinner.hint = AppLanguage.getString(hint_size)

        title.hint = AppLanguage.getString(hint_title)

        select_start_date_title.text = AppLanguage.getString(attr_start_at)
        start_at_date.text = AppLanguage.getString(txt_v_select_date)

        number_of_days.hint = AppLanguage.getString(hint_number_of_days)
        short_bio.hint = AppLanguage.getString(hint_content)

        request_ad.text = AppLanguage.getString(btn_request_ad)
    }

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

        uploadFileManager.onResult(requestCode, resultCode, this, data, 100) { sentFile, bitmap, _ ->
            selectedPhoto = bitmap
            val adDimen = adsDimens[size_spinner.selectedIndex]
            if (bitmap.height == adDimen.height && bitmap.width == adDimen.width) {
                selected_photo.setImageBitmap(bitmap)
            } else {
                Toast.makeText(context, AppLanguage.getString(attr_err_image_size) + "${adDimen.width}×${adDimen.height}",
                        Toast.LENGTH_LONG).show()
            }
        }
    }

    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) {
                UploadFileManager_Activity.CAMERA_STORAGE_REQUEST -> uploadFileManager.launchCamera(this)
                UploadFileManager_Activity.GALLERY_STORAGE_REQUEST -> uploadFileManager.launchGallery(this)
            }
        }
    }

    private fun reset() {
        selectedPhoto = null
        selected_photo.setImageBitmap(selectedPhoto)
        name.editText!!.setText("")
        email.editText!!.setText("")
        tel.editText!!.setText("")
        mobile.editText!!.setText("")
        type_spinner.setItems(adsTypes)
        size_spinner.setItems(adsDimens.names)
        title.editText!!.setText("")
        startAtDate = null
        start_at_date.text = AppLanguage.getString(txt_v_select_date)
        number_of_days.editText!!.setText("")
        short_bio.editText!!.setText("")
        scroll.smoothScrollTo(0, 0)
    }

}