/*
* fader.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 "fader.h"
#include "chrono.h"
extern const char spc;

using namespace std;

fader::fader (double dt) : afl (0) {
	set (0.0f, 1.0f, 0, dt);
}

fader::fader (float vs, float ve) : afl (0) {
  set (vs, ve, 0); 
}

void fader::load (ifstream& f) {
	f >> start >> end >> on >> delta >> flip >> delta_time >> reached;
	start_time = ui_clk ();
}

void fader::save (ofstream& f) {
	f << start << spc << end << spc << on << spc << delta << spc << flip << spc << delta_time << spc << reached;
}

void fader::set (float vs, float ve, int _on, double dt) {

  start = vs;
  end = ve;
  delta = end - start;

  alpha = 0;
  amount = start;

  delta_time = dt;

  on = _on;
	reached = 0;
	start_time = ui_clk ();

}

int fader::eval () {
  if (on) {
    double dt = ui_clk() - start_time;
		if (dt < delta_time) {
			alpha = dt * 1.0f / delta_time;
			amount = start + alpha * delta;
		} else {
      if (reached) {
        on = 0;
				if (afl) afl->after_fade (*this);
      } else {
        reached = 1;
        alpha = 1.0f;
				amount = end;
      }
    }
	}
  return on;
}

void fader::restart () {
  on = 1;
  reached = 0;
	alpha = 0;
	amount = start;
  start_time = ui_clk();
}

void fader::copy (fader* src) {

	if (src == 0) return;

  start = src->start;
  end = src->end;
  delta = src->delta;

  if (delta < 0) flip = 1; else flip = 0;

  alpha = src->alpha;
  amount = src->amount;

  delta_time = src->delta_time;

  on = src->on;
	reached = src->reached;
	start_time = src->start_time;

  afl = src->afl;

}

void fader::retime (double dt) {
  set (amount, end, 1, dt);
  /*start = amount;
  delta = end - start;
  alpha = 0;
  delta_time = dt;
  start_time = ui_clk ();*/
}
