package com.touchlock;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;

public class UnlockTouchListener implements OnTouchListener {

	private int defaultLeftMargin;
	private int deltaX;
	private LayoutParams lp;
	private ImageView lock;
	private boolean isOpen = false;
	private View border;

	public UnlockTouchListener(LayoutParams lp, ImageView lock, View border) {
		defaultLeftMargin = lp.leftMargin;
		this.lp = lp;
		this.lock = lock;
		this.border = border;
	}

	private void open() {
		lock.setImageResource(R.drawable.lock_open_w);
		isOpen = true;
	}

	private void close() {
		lock.setImageResource(R.drawable.lock_closed_w);
		isOpen = false;
	}

	@SuppressLint("ClickableViewAccessibility")
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		final int x = (int) event.getRawX();
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			deltaX = x - defaultLeftMargin;
			border.setBackgroundResource(R.drawable.shape_border);
			return true;
		case MotionEvent.ACTION_MOVE:
			int left = x - deltaX;
			if (left >= 0) {
				left = 0;
				if (!isOpen) {
					open();
					deltaX = 0 - defaultLeftMargin;
				}
			} else {
				if (isOpen) {
					close();
				}
			}
			lp.leftMargin = left;
			v.setLayoutParams(lp);
			return true;
		case MotionEvent.ACTION_UP:
			if (isOpen) {
				((Activity)v.getContext()).finish();
			} else {
				lp.leftMargin = defaultLeftMargin;
				v.setLayoutParams(lp);
				close();
				border.setBackgroundResource(0);
			}
			return true;
		default:
			return false;
		}

	}

}
