package com.kdanmobile.reader.screen.view

import android.content.Context
import android.graphics.drawable.GradientDrawable
import android.graphics.drawable.LayerDrawable
import android.graphics.drawable.StateListDrawable
import android.support.constraint.ConstraintLayout
import android.support.v4.content.ContextCompat
import android.util.AttributeSet
import android.view.LayoutInflater
import com.kdanmobile.reader.R
import kotlinx.android.synthetic.main.view_color_oval.view.*

class ColorOvalView : ConstraintLayout {

    var color: Int = android.R.color.black
        set(value) {
            field = value

            initColor(value)
        }

    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.ColorOvalView, 0, 0)
        color = typedArray.getColor(R.styleable.ColorOvalView_color, ContextCompat.getColor(context, android.R.color.black))
    }

    private fun initView() {
        LayoutInflater.from(context).inflate(R.layout.view_color_oval, this)
        initColor(color)
    }

    override fun setSelected(selected: Boolean) {
        super.setSelected(selected)

        colorOval.isSelected = selected
        initColor(color)
    }

    private fun initColor(color: Int) {
        colorOval?.apply {
            val stateListDrawable = background.mutate() as StateListDrawable
            val layerDrawable = stateListDrawable.current.mutate() as LayerDrawable
            val gradientDrawable = layerDrawable.findDrawableByLayerId(R.id.ovalColor).mutate() as GradientDrawable
            gradientDrawable.setColor(color)
        }
    }
}