package info.knacki.pass.ui.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.Checkable;
import android.widget.LinearLayout;

import info.knacki.pass.R;

@SuppressLint("ViewConstructor")
public class Checkbox extends LinearLayout implements Checkable {
    protected final AppCompatImageView fCheckbox;
    protected final AppCompatTextView fTextView;
    protected OnCheckedChangeListener fCheckedChangeListener;
    protected boolean fChecked;

    public interface OnCheckedChangeListener {
        void onCheckedChanged();
    }

    public Checkbox(Context ctx) {
        super(ctx);
        LayoutInflater.from(ctx).inflate(R.layout.checkbox, this, true);
        fCheckbox = findViewById(R.id.checkbox_check);
        fTextView = findViewById(R.id.checkbox_label);
    }

    public Checkbox(Context ctx, AttributeSet attrs) {
        super(ctx, attrs);
        LayoutInflater.from(ctx).inflate(R.layout.checkbox, this, true);
        fCheckbox = findViewById(R.id.checkbox_check);
        fTextView = findViewById(R.id.checkbox_label);

        final String textAttribute = getContext().getTheme().obtainStyledAttributes(attrs, R.styleable.Checkbox, 0, 0).getString(R.styleable.Checkbox_text);
        if (textAttribute != null)
            fTextView.setText(textAttribute);
    }

    public Checkbox(Context ctx, AttributeSet attrs, int style) {
        super(ctx, attrs, style);
        LayoutInflater.from(ctx).inflate(R.layout.checkbox, this, true);
        fCheckbox = findViewById(R.id.checkbox_check);
        fTextView = findViewById(R.id.checkbox_label);

        final String textAttribute = getContext().getTheme().obtainStyledAttributes(attrs, R.styleable.Checkbox, 0, 0).getString(R.styleable.Checkbox_text);
        if (textAttribute != null)
            fTextView.setText(textAttribute);
    }

    public Checkbox SetOnCheckedChangeListener(OnCheckedChangeListener onCheckedChangeListener) {
        fCheckedChangeListener = onCheckedChangeListener;
        return this;
    }

    private void SetIcon() {
        fCheckbox.setImageDrawable(getContext().getResources().getDrawable(fChecked ? android.R.drawable.checkbox_on_background : android.R.drawable.checkbox_off_background));
    }

    @Override
    public void setChecked(boolean checked) {
        if (fChecked != checked) {
            fChecked = checked;
            SetIcon();
            if (fCheckedChangeListener != null)
                fCheckedChangeListener.onCheckedChanged();
        }
    }

    @Override
    public boolean isChecked() {
        return fChecked;
    }

    @Override
    public void toggle() {
        setChecked(!isChecked());
    }
}
