package org.odk.collect.android.views.colorpicker;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.widget.AppCompatSeekBar;
import android.util.AttributeSet;
import android.view.ViewTreeObserver;
import android.widget.SeekBar;

/**
 * A modified AppCompatSeekBar that draws the HueRange as its background
 */
public class HuePicker extends AppCompatSeekBar {

  private static final int MIN_SIZE_DIP = 200;
  private boolean canUpdateHexVal = true;

  private static int minSizePx;
  private OnHuePickedListener onHuePickedListener;


  Context mContext;

  public HuePicker(Context context) {
    super(context);
    init(context);
  }

  public HuePicker(Context context, AttributeSet attrs) {
    super(context, attrs);
    init(context);
  }


  private void init(Context context) {
    minSizePx = (int) Stools.dipToPixels(context, MIN_SIZE_DIP);
    mContext = context;

    ViewTreeObserver vto = getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
      @Override
      public void onGlobalLayout() {
        HuePicker.this.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        setProgressDrawable(new BitmapDrawable(BitmapsGenerator.getHueBitmap
            (getMeasuredWidth(), getMeasuredHeight())));
      }
    });


    setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
      @Override
      public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        setHue(progress);
      }

      @Override
      public void onStartTrackingTouch(SeekBar seekBar) {

      }

      @Override
      public void onStopTrackingTouch(SeekBar seekBar) {

      }
    });


  }


  public void setHue(float hue) {
    if (onHuePickedListener != null) {
      onHuePickedListener.onPicked(hue);
    }
  }


  public void setOnHuePickedListener(OnHuePickedListener onHuePickedListener) {
    this.onHuePickedListener = onHuePickedListener;
  }

  public boolean isCanUpdateHexVal() {
    return canUpdateHexVal;
  }

  public void setCanUpdateHexVal(boolean canUpdateHexVal) {
    this.canUpdateHexVal = canUpdateHexVal;
  }


  public interface OnHuePickedListener {
    void onPicked(float hue);
  }
}
