/*
* autopause.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 "chrono.h"
#include "autopause.h"
#include "defvelaccel.h"
#include "autorotator.h"
#include "console.h"

autopauset::autopauset (defvelaccel& d) {
  a = 0;
  yes = d.autos.pause.yes;
  tar = d.autos.pause.tar;
  every = d.autos.pause.every ();
  f0r = d.autos.pause.f0r ();
  rndt[0] = d.autos.pause.every.rndrd;
  rndt[1] = d.autos.pause.f0r.rndrd;
  settrigt (0, every);
  settrigt (1, f0r);
  t[0] = &every;
  t[1] = &f0r;
  vt[0] = &d.autos.pause.every;
  vt[1] = &d.autos.pause.f0r; 
}

void autopauset::settrigt (int i, double& d) {
  alarmt& ai = alm[i];
  ai.triggert = d;
}

void autopauset::operator() (autorotator& ar) {
  alarmt &aa = alm[a];
  if (aa(ui_clk())) {
    aa.stop ();
    a = !a;
    double& ta = *t[a];
    if (rndt[a]) ta = (*vt[a])(1);
    int* tars [] = {&ar.yes, &ar.autoflip.yes};
    int& taryes = *tars[tar];
    taryes = !a;
    alarmt& nxt = alm[a];
    nxt.triggert = ta;
    nxt.start ();
  }
}

void autopauset::go () {
  a = 0;
  alm[a].start ();
}

void autopauset::setyes (int y, autorotator& ar) {
  yes = y;
  if (!yes && a) ar.setyes (1);
}

std::istream& operator>> (std::istream& file, autopauset& ap) {
  file >> ap.yes >> ap.rndt[0] >> ap.rndt[1];
  return file;
}

std::ostream& operator<< (std::ostream& file, autopauset& ap) {
  file << ap.yes << spc << ap.rndt[0] << spc << ap.rndt[1] << spc;
  return file;
}
