using UnityEngine;
using System.Collections;
using Framework.Entities;
using Framework.Extensions;
using System.Linq;
using System.Collections.Generic;
using Framework.InteractionSystem;
using Framework.Utility;
using Project.Triggers;
using Project.Player;

namespace Project.Actors
{
    public class DialogSpeaker : CoreBehaviour
    {
        public class AdvanceDialogAction : CoreAction { }

        public string currentLine;
        private int currentLineIndex;
        private string[] lines;

        public void AdvanceDialog()
        {
            this.currentLineIndex++;
        }

        // Use this for initialization
        protected override void InnerAwake()
        {
            AddActionHandler<DialogTrigger.StartDialogAction>(StartDialog);
        }

        // Update is called once per frame
        protected override void InnerUpdate()
        {
            if (this.lines != null)
            {

                if (this.currentLineIndex >= this.lines.Length)
                {
                    Announce(new PlayerInput.UnfreezeInputAction());
                    this.lines = null;
                    this.currentLine = "";
                }
                else
                {
                    this.currentLine = this.lines[this.currentLineIndex];
                }
            }
        }

        private void StartDialog(DialogTrigger.StartDialogAction action)
        {
            Debug.Log("Load: " + action.resourceName);
            TextAsset dialogFile = Resources.Load(action.resourceName) as TextAsset;
            if (dialogFile != null)
            {
                Debug.Log("File found");
                this.lines = dialogFile.text.Split('\n');
                //Debug.Log(string.Join(",", lines));
                if (this.lines.Length == 0)
                {
                    this.lines = null;
                }
                else
                {
                    Announce(new PlayerInput.FreezeInputAction());
                    this.currentLineIndex = 0;
                }
            }
        }
    }
}