package io.github.sdsstudios.ScoreKeeper.ViewHolders

import android.content.Context
import android.support.design.widget.TextInputLayout
import android.text.Editable
import android.text.TextWatcher
import io.github.sdsstudios.ScoreKeeper.R
import ir.coderz.ghostadapter.Binder
import kotlin.reflect.KMutableProperty0

/**
 * Created by sethsch1 on 06/11/17.
 */

abstract class EditTextItem<T>(
        val ctx: Context,
        private val mHintId: Int

) : BaseViewItem<T>() {

    private lateinit var mTextInputLayout: TextInputLayout

    @Binder
    open fun bind(viewHolder: EditTextHolder) {
        viewHolder.apply {
            mTextInputLayout = textInputLayout
            textInputLayout.hint = ctx.getString(mHintId)

            if (option != null) {
                editText.setText(option?.get().toString())

                editText.addTextChangedListener(object : TextWatcher {
                    override fun afterTextChanged(s: Editable?) {}
                    override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}

                    override fun onTextChanged(s: CharSequence?, p1: Int, p2: Int, p3: Int) {
                        if (s.isNullOrBlank() && option?.name != "notes") {
                            textInputLayout.error = ctx.getString(R.string.error_can_not_be_empty)
                            error = true
                            return
                        }

                        if (textInputLayout.error != null) {
                            textInputLayout.error = null
                            error = false
                        }

                        setData(option!!, s.toString(), textInputLayout)
                    }
                })
            }
        }
    }

    abstract fun setData(option: KMutableProperty0<T>,
                         data: String,
                         textInputLayout: TextInputLayout)

    override var error = false
        get() = mTextInputLayout.error != null
}