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.view.ViewGroup;
import android.widget.Checkable;
import android.widget.LinearLayout;

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

    public interface OnCheckedChangeListener {
        void onCheckedChanged(Checkbox checkbox, boolean isChecked);
    }

    public Checkbox(Context context, int text, OnCheckedChangeListener onCheckedChangeListener, ViewGroup parent) {
        super(context);
        setOrientation(HORIZONTAL);
        fCheckbox = new AppCompatImageView(context);
        fTextView = new AppCompatTextView(context);
        addView(fCheckbox);
        addView(fTextView);
        fTextView.setText(text);
        parent.addView(this);
        setOnClickListener(view -> toggle());
        setChecked(false);
        fCheckedChangeListener = onCheckedChangeListener;
    }

    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(this, isChecked());
        }
    }

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

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