using System;
using UnityEngine;

namespace Logic {
    public sealed class DialogProcessor {
        public string CurrentNodeId { get; private set; }
        public Node CurrentNode {
            get {
                return currentDialog.GetNode(CurrentNodeId);
            }
        }

        private Dialog currentDialog;
        private Container itemContainer;

        public DialogProcessor(Dialog dialog, Container container = null) {
            currentDialog = dialog;
            itemContainer = container ?? new Container();
            CurrentNodeId = currentDialog.startNodeId;
            CurrentNode.ProcessActions(itemContainer);
            if (CurrentNode.IsAutoSwitch) {
                SelectAutoSwitch();
            }
        }

        public void SelectAnswer(Answer answer) {
            if (CurrentNode == null) {
                Debug.LogError("current node is empty");
                return;
            }
            answer.ProcessActions(itemContainer);
            CurrentNodeId = answer.nextNodeId;
            if (CurrentNodeId == currentDialog.endNodeId) {
                return;
            }
            CurrentNode.ProcessActions(itemContainer);
            if (CurrentNode.IsAutoSwitch) {
                SelectAutoSwitch();
            }
        }

        private void SelectAutoSwitch() {
            var answers = CurrentNode.GetAvailableAnswers(itemContainer);
            SelectAnswer(answers[0]);
        }

        public bool IsDialogEnded() {
            return (CurrentNodeId == currentDialog.endNodeId);
        }
    }
}