using UnityEngine;
using System.Collections;
using Framework.Entities;
using System.Collections.Generic;

public class Journal : CoreBehaviour
{
    public static string[] LoadText(string fileName)
    {
        Debug.Log("Load: " + fileName);
        TextAsset dialogFile = Resources.Load(fileName) as TextAsset;
        if (dialogFile != null)
        {
            Debug.Log("File found");
            return dialogFile.text.Split('\n');
        }
        return null;
    }

    public class AddEntryAction : CoreAction
    {
        public string entry;

        public AddEntryAction(string entry)
        {
            this.entry = entry;
        }
    }

    public class UpdatedAction : CoreAction { }

    public int pageMaxEntryCount = 6;
    private int entryNumber = 0;
    public List<List<string>> pages;

    public List<string> GetCurrentPage()
    {
        return pages[pages.Count - 1];
    }

    protected override void InnerAwake()
    {
        AddGlobalActionHandler<AddEntryAction>(this, AddEntry);
        this.pages = new List<List<string>>();
        this.pages.Add(new List<string>());
    }

    protected override void InnerStart()
    {
        AddEntry(new AddEntryAction(Journal.LoadText("Intro")[0]));
    }

    protected override void InnerUpdate()
    {
        
    }

    private void AddEntry(AddEntryAction action)
    {
        int total = 0;
        entryNumber++;
        GetCurrentPage().ForEach(i => total += i.Length);
        if (total >= 400) // GetCurrentPage().Count() >= this.pageMaxEntryCount
        {
            this.pages.Add(new List<string>());
        }
        GetCurrentPage().Add("Entry " + entryNumber +"\n" + action.entry + "\n"); //(((this.pages.Count - 1) * this.pageMaxEntryCount) + GetCurrentPage().Count + 1)
        Announce(new UpdatedAction());
    }
}
