package com.viaccessorca.voplayerdemo.quickaction;

import android.content.Context;
import android.graphics.Rect;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.viaccessorca.voplayerdemo.R;

public class SliderPopup extends PopupWindows implements OnDismissListener, OnSeekBarChangeListener, OnClickListener {


	/**
	 * Listener for window dismiss
	 *
	 */
	public interface OnSliderPopupDismissListener {
		public abstract void onSliderDismiss(int newValue);
	}
	
	/**
	 * Listener for slider update dismiss
	 *
	 */
	public interface OnSliderPopupUpdateListener {
		public abstract void onSliderUpdate(int newValue);
	}
	
	/**
	 * Listener for button click
	 */
	public interface OnSliderButtonClickListener {
		public abstract void onSliderBtnClick();
	}

	private final static String TAG = "SliderPopup";

	private View mRootView;

	private LayoutInflater mInflater;

	private ScrollView mScroller;
	private OnSliderPopupDismissListener sliderDismissedListener;
	private OnSliderPopupUpdateListener sliderUpdatedListener;
	private OnSliderButtonClickListener sliderBtnClickListener;

	private SeekBar sliderSeekBar;
	private TextView sliderValueText;
	private TextView sliderUIText;
	private Button sliderButton;

	private int rootWidth=0;

	public static final int VERTICAL = 1;

	private static final int DEFAULT_SLIDER_MAX_VALUE = 4000;
	private static final int DEFAULT_SLIDER_STEP_SIZE = 100;

	private int sliderMaxValue = DEFAULT_SLIDER_MAX_VALUE;
	private int sliderStepSize = DEFAULT_SLIDER_STEP_SIZE;

	public int index_to_launch;
	public View actionAnchor;
	public Context actionContext;

	private int sliderMinValue;
	private String sliderText;
	
	private boolean discardNextDismissEvent = false;

	/**
	 * Constructor for default vertical layout
	 *
	 * @param context Context
	 */
	public SliderPopup(Context context) {
		this(context, VERTICAL);
	}

	/**
	 * Constructor allowing orientation override
	 *
	 * @param context Context
	 * @param orientation Layout orientation, can be vartical or horizontal
	 */
	public SliderPopup(Context context, int orientation) {
		super(context);
		actionContext = context;
		index_to_launch = -1;
		mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		setRootViewId(R.layout.sliderpopup_view);
	}


	/**
	 * Set root view.
	 *
	 * @param id Layout resource id
	 */
	public void setRootViewId(int id) {
		mRootView = (ViewGroup) mInflater.inflate(id, null);

		sliderSeekBar = (SeekBar)mRootView.findViewById(R.id.slider_seekbar);
		sliderValueText = (TextView)mRootView.findViewById(R.id.slider_value_text);
		sliderUIText = (TextView)mRootView.findViewById(R.id.slider_text);
		sliderButton = (Button)mRootView.findViewById(R.id.slider_btn);

		sliderSeekBar.setMax(sliderMaxValue);
		sliderSeekBar.setSecondaryProgress(sliderMinValue);
		sliderSeekBar.setOnSeekBarChangeListener(this);

		sliderButton.setOnClickListener(this);

		sliderUIText.setText(sliderText);

		mRootView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		setContentView(mRootView);
	}

	/**
	 * Show quickaction popup. Popup is automatically positioned, on top or bottom of anchor view.
	 *
	 */
	public void show (View anchor, int startProgress) {
		preShow();
		
		sliderSeekBar.setProgress(startProgress);
		sliderValueText.setText("" + startProgress);

		int xPos, yPos;

		int[] location = new int[2];

		anchor.getLocationOnScreen(location);
		Rect anchorRect = new Rect(location[0], location[1], location[0] + anchor.getWidth(), location[1]
		                                                  + anchor.getHeight());

		mRootView.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

		int rootHeight = mRootView.getMeasuredHeight();

		if (rootWidth == 0) {
			rootWidth = mRootView.getMeasuredWidth();
		}

		int screenWidth = mWindowManager.getDefaultDisplay().getWidth();
		int screenHeight = mWindowManager.getDefaultDisplay().getHeight();

		// Automatically get X coord of popup (top left)
		if ((anchorRect.left + rootWidth) > screenWidth) {
			xPos = anchorRect.left - (rootWidth-anchor.getWidth());
			xPos = (xPos < 0) ? 0 : xPos;

		} else {
			if (anchor.getWidth() > rootWidth) {
				xPos = anchorRect.centerX() - (rootWidth/2);
			} else {
				xPos = anchorRect.left;
			}
		}

		int dyTop = anchorRect.top;
		int dyBottom = screenHeight - anchorRect.bottom;

		boolean onTop = (dyTop > dyBottom) ? true : false;

		if (onTop) {
			if (rootHeight > dyTop) {
				yPos = 0;
				LayoutParams l = mScroller.getLayoutParams();
				l.height = dyTop - anchor.getHeight();
			} else {
				yPos = anchorRect.centerY() - rootHeight;
			}
		} else {			
			yPos = anchorRect.centerY();
			if (rootHeight > dyBottom) {
				LayoutParams l = mScroller.getLayoutParams();
				l.height = dyBottom;
			}
		}
		mWindow.showAtLocation(anchor, Gravity.NO_GRAVITY, xPos, yPos);
		this.sliderSeekBar.setOnSeekBarChangeListener(this);
	}

	public void setSliderMaxValue(int maxValue) {
		this.sliderMaxValue = maxValue;
		if(null != sliderSeekBar) {
			sliderSeekBar.setMax(sliderMaxValue);
		}
	}

	public void setSliderStepSize(int stepSize) {
		this.sliderStepSize = stepSize;
	}
	
	public void setSliderMinValue(int minValue) {
		this.sliderMinValue = minValue;
		if(null != sliderSeekBar) {
			sliderSeekBar.setSecondaryProgress(sliderMinValue);
		}
	}
	
	public void setSliderText(String text) {
		sliderText = text;
		if(null != sliderUIText) {
			sliderUIText.setText(text);
		}
	}

	public void setSliderBtn(boolean visible, String text) {
		if(visible) {
			sliderButton.setText(text);
			sliderButton.setVisibility(View.VISIBLE);
		}
		else {
			sliderButton.setVisibility(View.GONE);
		}
	}

	/**
	 * Set listener for window dismissed. This listener will only be fired if the quickaction dialog is dismissed
	 * by clicking outside the dialog or clicking on sticky item.
	 */
	public void setOnDismissListener(SliderPopup.OnSliderPopupDismissListener listener) {
		setOnDismissListener(this);
		sliderDismissedListener = listener;
	}
	
	public void setOnBtnClickListener(SliderPopup.OnSliderButtonClickListener listener) {
		sliderBtnClickListener = listener;
	}

	/**
	 * Set listener for window update. This listener will only be fired if the quicakction dialog is updated.
	 */
	public void setOnUpdateListener(SliderPopup.OnSliderPopupUpdateListener listener) {	
		sliderUpdatedListener = listener;
	}

	public void onDismiss() {
		Log.d(TAG, "onDismiss");
		if ((sliderDismissedListener != null) && !discardNextDismissEvent ) {
			sliderDismissedListener.onSliderDismiss(this.sliderSeekBar.getProgress());
		}
		discardNextDismissEvent = false;
	}


	@Override
	public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
		if(fromUser) {

			progress = ((int)Math.round(progress/(double)sliderStepSize))*sliderStepSize;
			
			if(progress < sliderMinValue) {
				progress = sliderMinValue;
			}
			seekBar.setProgress(progress);
			sliderValueText.setText(progress + "");
			
            if (sliderUpdatedListener != null) {
                sliderUpdatedListener.onSliderUpdate(this.sliderSeekBar.getProgress());
		}		
			
		}
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {

		Log.d(TAG, "onStartTrackingTouch");
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {

		Log.d(TAG, "onStopTrackingTouch");

		int progress = ((int)Math.round(seekBar.getProgress()/(double)sliderStepSize))*sliderStepSize;

		if(progress < sliderMinValue) {
			progress = sliderMinValue;
		}
		sliderValueText.setText(progress + "");
		seekBar.setProgress(progress);
		seekBar.setOnSeekBarChangeListener(null);
		this.dismiss();
	}

	@Override
	public void onClick(View v) {
		if(null != sliderBtnClickListener) {
			sliderBtnClickListener.onSliderBtnClick();
		}
	}
	
	public void userDismiss() {
		discardNextDismissEvent = true;
		dismiss();
	}
}
