/*
* plugin.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 "plugin.h"
#include "curve_editor.h"
#include "vector2d.h"
#include "ui_list.h"
#include "field.h"
#include "viewwin.h"
#include "console.h"
#include "log.h"

#include <vector>
#include <fstream>
using namespace std;

plugin::plugin () {
	name = "from_plugin";
	ss.str (name);
  num_ctrls = 0;
  shapeform = 1;
  pts = 0;
  pts_n = 0;
	mix = 1;
	undo = 1;
	ed = 0;
	npts = 0;
}

void plugin::setup () {

  num_ctrls = 2;
  ctrls.resize (num_ctrls);
  ctrls[0] = &cb_auto_apply;
  ctrls[1] = &b_apply;

  b_apply.set_text ("Apply");
  cb_auto_apply.set_text ("Auto apply");

  b_apply.set_listener (this);
  cb_auto_apply.set_listener (this);

	b_apply.click_repeat = 1;

	ss.precision (10);

}

void plugin::update () {
  for (int i = 0; i < num_ctrls; ++i) ctrls[i]->update ();
}

int plugin::handle_input () {
  int r = 0;
  if (!_folded) for (int i = 0; i < num_ctrls; ++i) r |= ctrls[i]->handle_input ();
  return r;
}

void plugin::draw () {
  if (!_folded) for (int i = 0; i < num_ctrls; ++i) ctrls[i]->draw ();
}


void plugin::clicked (button& b) {
	uis.crved->apply_plugin (this);
}

void plugin::changed (field& f) {
  do_render ();
}

void plugin::changed (checkbutton& cb) {
  if (&cb == &cb_auto_apply) {
    if (cb.state) {
      uis.crved->apply_plugin (this);
			mix = undo = 0;
    } else mix = undo = 1;
  }
}

void plugin::try_auto_apply () {
	//if (cb_auto_apply.state) uis.crved->apply_plugin (this);
  if (cb_auto_apply.state) ed->apply_plugin (this);
}

void plugin::try_auto_apply (curve_editor* ed) {
  if (cb_auto_apply.state) ed->apply_plugin (this);
}

void plugin::unfold () {
  for (int i = 0, j = num_ctrls; i < j; ++i) ctrls[i]->show ();
  _folded = 0;
}

void plugin::fold () {
  for (int i = 0, j = num_ctrls; i < j; ++i) ctrls[i]->hide ();
  _folded = 1;
}

void plugin::draw (curve_editor* ed) {
  glColor3f (clr.r, clr.g, clr.b);
  glVertexPointer (2, GL_FLOAT, 0, pts);
  glDrawArrays (GL_LINE_STRIP, 0, npts);
}

plugin::~plugin () {
  if (pts) delete[] pts;
}

string plugin::make_fname () {
  extern string user_data_dir;
  return (user_data_dir + "p_" + name);
}

void plugin::gen_pts () {
	if (ed) {
		npts = points.size ();
		if (pts_n < npts) {
			if (pts) delete[] pts;
			pts_n = npts;
			pts = new float [2 * pts_n];
		}
		float wx, wy;
		for (int i = 0, k = 0; i < npts; ++i) {
			point<float>& p = points[i];
			ed->obj2win (p.x, p.y, wx, wy);
			pts[k++] = wx; pts[k++] = wy;
		}
	}
}

void plugin::set_ed (curve_editor* e) {
	ed = e;
	gen_pts ();
}

void plugin::do_render () {
  render ();
  try_auto_apply ();
}

void plugin::do_render (curve_editor* ed) {
  render ();
  try_auto_apply (ed);
}
