// speech synthesis interface subsystem
//
// Written by Torsten Dreyer, started April 2014
//
// SPDX-License-Identifier: GPL-2.0-or-later
// SPDX-FileCopyrightText: 2014 Torsten Dreyer

#include "config.h"

#include "flitevoice.hxx"
#include <Main/fg_props.hxx>
#include <simgear/sound/sample_group.hxx>
#include <flite_hts_engine.h>

using std::string;

#include "VoiceSynthesizer.hxx"

FGFLITEVoice::FGFLITEVoice(FGVoiceMgr * mgr, const SGPropertyNode_ptr node, const char * sampleGroupRefName)
    : FGVoice(mgr), _synthesizer( NULL), _seconds_to_run(0.0)
{

  _sampleName = node->getStringValue("desc", node->getPath().c_str());

    SGPath voice = globals->get_fg_root() / "ATC" /
      node->getStringValue("htsvoice", "cmu_us_arctic_slt.htsvoice");

  _synthesizer = new FLITEVoiceSynthesizer(voice.utf8Str());

  auto smgr = globals->get_subsystem<SGSoundMgr>();
  _sgr = smgr->find(sampleGroupRefName, true);
  _sgr->tie_to_listener();

  node->getNode("text", true)->addChangeListener(this);

  SG_LOG(SG_SOUND, SG_DEBUG, "FLITEVoice initialized for sample-group '" << sampleGroupRefName
      << "'. Samples will be named '" << _sampleName << "' "
      << "voice is '" << voice << "'");
}

FGFLITEVoice::~FGFLITEVoice()
{
  delete _synthesizer;
}

void FGFLITEVoice::speak(const string & msg)
{
  // this is called from voice.cxx:FGVoiceMgr::FGVoiceThread::run
  string s = simgear::strutils::strip(msg);
  if (!s.empty()) {
    _sampleQueue.push(_synthesizer->synthesize(msg, 1.0, 0.5, 0.5));
  }
}

void FGFLITEVoice::update(double dt)
{
  _seconds_to_run -= dt;

  if (_seconds_to_run < 0.0) {
    SGSharedPtr<SGSoundSample> sample = _sampleQueue.pop();
    if (sample.valid()) {
      _sgr->remove(_sampleName);
      _sgr->add(sample, _sampleName);
      _sgr->resume();
      _sgr->play(_sampleName, false);

      // Don't play any further TTS until we've finished playing this sample,
      // allowing 500ms for a gap between transmissions.  Good radio comms!
      _seconds_to_run = 0.5 +  ((float) sample->get_no_samples()) / ((float) sample->get_frequency());
  }
  }
}
