/*
* box_selector.cc
* DIN Is Noise is copyright (c) 2006-2022 Jagannathan Sampath
* DIN Is Noise is released under GNU Public License 2.0
* For more information, please visit https://dinisnoise.org/
*/
#include "box_selector.h"
#include "random.h"
#include "container.h"
#include "console.h"

box_selector::box_selector () {
	op = NONE;
	cross = 0;
	lis = 0;
	lmb_clicked = 0;
	rmb_clicked = 0;
}

int box_selector::handle_input () {
	if (is_lmb (this)) {
		if (lmb_clicked == 0) {
			if (op == NONE) {
				op = EXISTS;
				is_lmb.tie = this;
				if (lis) lis->region_begin ();
			} else if (op == EXISTS) {
				op = FINISH;
			}
			lmb_clicked = 1;
		}
	} else {
		lmb_clicked = rmb_clicked = 0;
		if (op == EXISTS) {
			if (lis) lis->region_update ();
		} else if (op == FINISH) {
			is_lmb.clear (this);
			if (lis) lis->region_end ();
			op = NONE;
		}
	}
	return 1;
}


void box_selector::draw (const box<float>& region) {
	if (op == EXISTS) {
		glEnable (GL_LINE_STIPPLE);
		glLineStipple (1, 0xf00f);
		glColor3f (1, 1, 1);
		boxp[0]=region.left;boxp[1]=region.bottom;
		boxp[2]=region.right;boxp[3]=region.bottom;
		boxp[4]=region.right;boxp[5]=region.top;
		boxp[6]=region.left;boxp[7]=region.top;
		glVertexPointer (2, GL_FLOAT, 0, boxp);
		glDrawArrays (GL_LINE_LOOP, 0, 4);
		if (cross) {
      glColor3f (0.25, 0.25, 0.25);
			int my = (region.bottom + region.top) / 2.0 + 0.5;
			boxp[0]=region.left;boxp[1]=my;
			boxp[2]=region.right;boxp[3]=my;
			glDrawArrays (GL_LINES, 0, 2);
			int mx = (region.left + region.right) / 2.0 + 0.5;
			boxp[0]=mx;boxp[1]=region.bottom;
			boxp[2]=mx;boxp[3]=region.top;
			glDrawArrays (GL_LINES, 0, 2);
		}
		glDisable (GL_LINE_STIPPLE);
	}
}

int box_selector::abort () {
	if (op != NONE) {
		op = NONE;
		is_lmb.clear (this);
		if (lis) lis->region_abort ();
		return 1;
	}
	return 0;
}
