package com.hanwha.morakmorak.ui.main.home.post

import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.EditText
import com.hanwha.morakmorak.core.BaseViewModel
import com.hanwha.morakmorak.data.local.preferences.UserPreferences
import com.hanwha.morakmorak.data.remote.api.HomeAPI
import com.hanwha.morakmorak.data.remote.model.HomeCategory
import com.hanwha.morakmorak.extensions.with
import com.hanwha.morakmorak.util.NotNullMutableLiveData
import timber.log.Timber
import java.io.UnsupportedEncodingException
import java.nio.charset.Charset

/**
 * Created by aaron on 2019-09-17
 */
class HomePostViewModel(private val api: HomeAPI, private val prefs: UserPreferences) : BaseViewModel() {

    lateinit var onCalendarClick: (View) -> Unit
    lateinit var onPhotoClick: (View) -> Unit
    lateinit var onCameraClick: (View) -> Unit
    lateinit var onDialogCloseClick: (View) -> Unit
    lateinit var onDialogNegativeClick: (View) -> Unit
    lateinit var onDialogPositiveClick: (View) -> Unit
    lateinit var onCompletePost: (Boolean) -> Unit

    val title: NotNullMutableLiveData<String> = NotNullMutableLiveData("")
    val body: NotNullMutableLiveData<String> = NotNullMutableLiveData("")
    val dateTime: NotNullMutableLiveData<String> = NotNullMutableLiveData("")
    val location: NotNullMutableLiveData<String> = NotNullMutableLiveData("")
    val maxPerson: NotNullMutableLiveData<String> = NotNullMutableLiveData("")
    val cover: NotNullMutableLiveData<String> = NotNullMutableLiveData("")

    val isToolVisibility: NotNullMutableLiveData<Boolean> = NotNullMutableLiveData(false)

    val byteText: NotNullMutableLiveData<String> = NotNullMutableLiveData("0/1,000byte")

    val textChangedListener: (EditText) -> TextWatcher = { it ->
        (object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                val afterText = s.toString()
                try {
                    val bytes = afterText.toByteArray(Charset.forName(CHARSET))
                    if (bytes.size > 1000) {
                        s?.delete(s.length - 2, s.length - 1)
                    }
                } catch (e: UnsupportedEncodingException) {
                    e.printStackTrace()
                }
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (it.isFocusable) {
                    try {
                        val bytes = it.text.toString().toByteArray(Charset.forName(CHARSET))
                        byteText.value = "${bytes.size}/1,000bytes"
                    } catch (e: UnsupportedEncodingException) {
                        e.printStackTrace()
                    }
                }
            }
        })}

    fun postParty() {
        val params = mutableMapOf<String, Any>(
                "who" to prefs.userId,
                "what" to title.value,
                "when" to dateTime.value,
                "why" to body.value,
                "where" to location.value,
                "maxPerson" to maxPerson.value.toInt(),
                "category" to HomeCategory.MEETING.category,
                "cover" to cover.value.toInt()
        )

        addToDisposable(api.postParty(params).with()
                .doOnSubscribe { isProgressVisible.value = true }
                .doOnSuccess { isProgressVisible.value = false }
                .doOnError { isProgressVisible.value = false }
                .subscribe({
                    Timber.i("onSuccess")
                    onCompletePost(true)
                }, {
                    Timber.i("onError")
                    Timber.i(it)
                    onCompletePost(false)
                })
        )
    }

    companion object {
        const val CHARSET = "KSC5601"
    }

}