#pragma once

#if not defined(ARDUINO_ARCH_ESP32) 

#include <Automaton.h>

#include <EthernetUdp.h>
#include <OSCMessage.h>
#include <OSCBundle.h>

class Atm_out : public Machine {
 public:
  enum { IDLE, ON, START, BLINK_OFF, LOOP, DONE, OFF, WT_ON, WT_START };
  enum { EVT_ON_TIMER, EVT_OFF_TIMER, EVT_WT_TIMER, EVT_COUNTER, EVT_ON, EVT_OFF, EVT_BLINK, EVT_TOGGLE, EVT_TOGGLE_BLINK, ELSE, EVT_BRUP, EVT_BRDN }; // BRUP/BRDN pseudo
  enum { EVT_START = EVT_BLINK };

  Atm_out( void ) : Machine(){};
  Atm_out& begin( int attached_pin, bool activeLow,
          EthernetUDP& udpRef, OSCBundle& bndl, const char* address  );
  Atm_out& blink( void );
  Atm_out& blink( uint32_t duration );
  Atm_out& blink( uint32_t duration, uint32_t pause_duration, uint16_t repeat_count = ATM_COUNTER_OFF );
  Atm_out& pwm( uint16_t width, float freq = -1 );
  Atm_out& frequency( float freq );
  Atm_out& pause( uint32_t duration );
  Atm_out& fade( int fade );
  Atm_out& lead( uint32_t ms );
  Atm_out& repeat( uint16_t repeat );
  int brightness( int level = -1 );
  Atm_out& on( void );
  Atm_out& off( void );
  Atm_out& toggle( void );
  Atm_out& toggleBlink( void );
  Atm_out& start( void );
  Atm_out& trace( Stream& stream );
  Atm_out& onFinish( Machine& machine, int event = 0 );
  Atm_out& onFinish( atm_cb_push_t callback, int idx = 0 );
  Atm_out& range( int toLow, int toHigh, bool wrap = false );
  Atm_out& levels( unsigned char* map, int mapsize, bool wrap = false );
  int brighten( int v = 1 );
  Atm_out& trigger( int event );

  const char* _adress = "/OSC";
  EthernetUDP* _udpRef ;
  Atm_out& onOSC(OSCMessage& msg );
  OSCBundle* _bndl;


 private:
  enum { ENT_INIT, ENT_ON, ENT_OFF, EXT_CHAIN };
  uint8_t level;
  short pin;
  bool activeLow;
  uint8_t toHigh, toLow;
  bool wrap;
  uint16_t repeat_count;
  uint16_t width;
  float freq;
  atm_timer_millis on_timer, off_timer, lead_timer;
  atm_counter counter;
  atm_connector onfinish;
  unsigned char* levelMap;
  int levelMapSize;
  int mapLevel( int level );


  int event( int id );
  void action( int id );
};

#endif