package org.studiorailgun.kobold;

import java.util.concurrent.TimeUnit;

/**
 * Prints the response from a kobold request
 */
public class KoboldPrinter {
    
    /**
     * The number of milliseconds to wait between printing characters
     */
    static final int CHAR_DELAY = 10;

    /**
     * The interval to check at in milliseconds
     */
    static final int CHECK_INTERVAL = 300;

    /**
     * The request to print
     */
    KoboldRequest request;

    /**
     * Position of the printer (how many characters has it printed)
     */
    int position = 0;

    /**
     * Constructor
     */
    public KoboldPrinter(KoboldRequest request){
        this.request = request;
    }

    /**
     * Prints the request. Blocks the thread until the printing has finished.
     */
    public void print(){
        int i = 0;
        while(!this.request.isCompleted() || position < this.request.getResponse().length()){
            try {
                TimeUnit.MILLISECONDS.sleep(CHAR_DELAY);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if(!this.request.isCompleted() && i % (CHECK_INTERVAL / CHAR_DELAY) == 0){
                this.request.check();
            }
            if(this.position < this.request.getResponse().length()){
                System.out.print(this.request.getResponse().charAt(this.position));
                this.position++;
            }
            //check for occurrences of immediate dialong ending symbols
            if(KoboldSymbols.containsBannedSymbol(this.request.getResponse())){
                String message = KoboldSymbols.removeBannedSymbol(this.request.getResponse());
                this.request.markCompleted();
                System.out.print("\r" + message);
                break;
            }
            i++;
        }
        //make sure we're on a fresh line
        System.out.println();
    }

}
