export class Typer {

    target;
    texts;
    typingDelay;
    deletionDelay;
    pauseAfterWord = 2000;
    pauseBetweenWords = 500;

    textIndex = 0;
    charIndex = 0;
    deleting = false;

    /**
     *
     * @param target
     * @param texts
     * @param typingDelay
     * @param deletionDelay
     */
    constructor({ target : target, texts : texts, typingDelay : typingDelay, deletionDelay : deletionDelay }) {
        this.target = target;
        this.texts = texts;
        this.typingDelay = typingDelay;
        this.deletionDelay = deletionDelay;
    }

    start(){
        if (!this.deleting) {
            this.addText();
        } else {
            this.removeText();
        }
    }

    addText(){
        const currentText = this.texts[this.textIndex];
        this.charIndex++;
        this.target.innerText = currentText.slice(0, this.charIndex);

        if (this.charIndex === currentText.length) {
            this.deleting = true;
            setTimeout(() => this.start(), this.pauseAfterWord);
        } else {
            setTimeout(() => this.start(), this.typingDelay);
        }
    }

    removeText(){
        const currentText = this.texts[this.textIndex];
        this.charIndex--;
        this.target.innerText = currentText.slice(0, this.charIndex);

        if (this.charIndex === 0) {
            this.deleting = false;
            this.textIndex = (this.textIndex + 1) % this.texts.length;
            setTimeout(() => this.start(), this.pauseBetweenWords);
        } else {
            setTimeout(() => this.start(), this.deletionDelay);
        }
    }
}