package com.fitbot.speech;

import java.util.Arrays;
import java.util.Locale;
import com.aldebaran.qi.sdk.builder.SayBuilder;
import com.aldebaran.qi.sdk.object.conversation.Phrase;
import com.aldebaran.qi.sdk.object.conversation.Say;
import com.aldebaran.qi.sdk.object.locale.Language;
import com.aldebaran.qi.sdk.object.locale.Locale;
import com.aldebaran.qi.sdk.object.locale.Region;


public class SpeechGenerator  {

    private QiContext qiContext;                              // The QiContext object
    private ISpeechCallback speechCallback = (content) -> {}; // Default empty callback
    private StringBuilder speechBuffer = new StringBuilder(); // Buffer to store the speech content
    private String languageIso639_1;                          // ISO 639-1 language code

    /**
     * Constructor that sets the language of the speech to be generated
     * @param languageIso639_1 The ISO 639-1 language code, e.g. "en" for English
     */
    public SpeechGenerator(String languageIso639_1)
    {
        if ( !Arrays.asList(Locale.getISOLanguages()).contains(languageIso639_1) )
            throw new IllegalArgumentException("Invalid language code");
        this.languageIso639_1 = languageIso639_1;
    }

    /**
     * Default constructor, sets the language to Dutch
     */
    public SpeechGenerator()
    {
        this("nl");
    }


    /**
     * Set the language of the speech to be generated
     * @param languageIso639_1 The ISO 639-1 language code, e.g. "en" for English
     * @return An instance of the SpeechGenerator class
     */
    public SpeechGenerator language(String languageIso639_1)
    {
        this.languageIso639_1 = languageIso639_1;
        return this;
    }

    /**
     * Appends the provided text to the speech buffer
     * @param text The text to append
     * @return An instance of the SpeechGenerator class
     */
    public SpeechGenerator print(String text)
    {
        speechBuffer.append(text);
        return this;
    }

    /**
     * Appends the provided text to the speech buffer, followed by a newline character
     * @param text The text to append
     * @return An instance of the SpeechGenerator class
     */
    public SpeechGenerator println(String text)
    {
        return print(text).print("\n");
    }

    /**
     * Get the contents of the speech buffer
     */
    public String getBuffer()
    {
        return speechBuffer.toString();
    }

    /**
     * Clear the contents of the speech buffer
     */
    public void clearBuffer()
    {
        speechBuffer = new StringBuilder();
    }

    /**
     * Print the contents of the speech buffer to the console
     */
    public void speak()
    {
        Say say = new SayBuilder().with(qiContext)
                .withPhrase(speechBuffer.toString())
                .withLocale(new Locale(languageIso639_1))
                .build();
        speechCallback.onSpeechGenerated(speechBuffer.toString());
    }


}
