package com.kdanmobile.reader.screen.view

import android.content.Context
import android.support.constraint.ConstraintLayout
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.CompoundButton
import com.kdanmobile.reader.R
import kotlinx.android.synthetic.main.view_row_switch.view.*

class RowSwitchView : ConstraintLayout {
    var text = ""

    var isChecked = false
        set(value) {
            field = value
            rowSwitchView_switch?.isChecked = isChecked
        }

    var onCheckedChangeListener: CompoundButton.OnCheckedChangeListener? = null
        set(value) {
            field = value
            rowSwitchView_switch?.setOnCheckedChangeListener(onCheckedChangeListener)
        }

    constructor(context: Context) : super(context) {
        initView()
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        initAttr(attrs)
        initView()
    }

    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
        initAttr(attrs)
        initView()
    }

    private fun initAttr(attributeSet: AttributeSet) {
        val typedArray = context.theme.obtainStyledAttributes(attributeSet, R.styleable.RowSwitchView, 0, 0)
        text = typedArray.getString(R.styleable.RowSwitchView_text)
        isChecked = typedArray.getBoolean(R.styleable.RowSwitchView_isChecked, false)
    }

    private fun initView() {
        LayoutInflater.from(context).inflate(R.layout.view_row_switch, this)
        rowSwitchView_text.text = text
        rowSwitchView_switch.isChecked = isChecked
    }
}