/*
* curve_picker.cc
* DIN Is Noise is copyright (c) 2006-2024 Jagannathan Sampath
* DIN Is Noise is released under GNU Public License 2.0
* For more information, please visit https://dinisnoise.org/
*/
#include "curve_picker.h"
#include "curve_editor.h"
#include "ui_list.h"
#include "input.h"
#include "log.h"
#include "console.h"
#include <vector>
#include <fstream>
using namespace std;

extern ui_list uis;
extern int mousex, mousey, mouseyy;
extern curve_picker_t curve_picker;
extern const char SPC;

extern void makefam (widget* parent, widget* children, int n);

void curve_picker_t::setup () {
  title.set_text ("Pick what?");
  widget* chld [] = {&pick, &cancel, &comps};
	makefam (&title, chld, 3);
  widget* w [] = {&title, &pick, &cancel, &comps};
  widget_load ("d_curve_picker", w, 4);
  cancel.set_text ("Cancel");
  pick.set_text ("Pick");
  LISTEN(pick, this);
  LISTEN(cancel, this);
  LISTEN(comps, this);
	n = 0;
	id = 0;
}

curve_picker_t::~curve_picker_t () {
  widget* w [] = {&title, &pick, &cancel, &comps};
  widget_save ("d_curve_picker", w, 4);
}

int curve_picker_t::handle_input () {
  if (!visible) return 0;
  widget* w [] = {&pick, &comps, &cancel, &title,};
	if (keypressed (SDLK_ESCAPE)) clicked (cancel);
  if (keypressed (SDLK_RETURN)) clicked (pick); 
	int r = 0;
  for (int i = 0; i < 4;++i) {
		r = w[i]->handle_input ();
		if (r) break;
	}
  return r;
}

void curve_picker_t::draw () {
  glEnable (GL_BLEND);
  glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glColor4f (0, 0, 0, 0.7f);
    glRecti (bg.left, bg.bottom, bg.right, bg.top);
  glDisable (GL_BLEND);
  widget* w [] = {&title, &pick, &cancel, &comps};
  for (int i = 0; i < 4;++i) w[i]->draw ();
  if (comps.hov != -1) curve_picker.id = comps.hov;
}

void curve_picker_t::show () {
	id = 0;
  if (CRVED) n = CRVED->hitlist.size (); else n = 0;
	if (id < n) { 
		widget::show ();
		int cx = title.extents.left, cy = title.extents.bottom;
		title.move (mousex - cx, mouseyy - cy); // move picker to mouse loc
		hit_t::name_only = (CRVED->todo == curve_editor::PICK_CURVE);
    comps.clear ();
    for (int i = 0; i < n; ++i) {
      hit_t& hi = CRVED->hitlist[i];
      stringstream ss; ss << hi;
      comps.add (ss.str());
    }
    comps.set_pos (title.posx, cancel.posy);
		calc_bg ();
	}
}

void curve_picker_t::hide () {
	widget::hide ();
	defocus (this);
}

void curve_picker_t::calc_bg () {
  const int delta = 1;
  bg.left = title.extents.left - delta;
  bg.top = title.extents.top + delta;
  bg.right = max (cancel.extents.right, comps.extents.right) + delta;
  bg.bottom = comps.extents.bottom - delta;
	set_focus (this);
}

void curve_picker_t::clicked (button& b) {
  if (&b == &comps || &b == &pick) CRVED->picked_using_picker (id); 
  curve_picker.hide ();
}
