﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using System.IO;

namespace Arugula.Games
{
    [CreateAssetMenu(fileName = "NameGenerator.asset", menuName = "Arugula/Name Generator")]
    public class NameGenerator : ScriptableObject
    {
        [System.Serializable]
        public class Name
        {
            public string name;
            public List<string> tags = new List<string>();

            public Name(string name)
            {
                this.name = name;
            }
        }

        public TextAsset[] textSources;
        private bool initialized = false;

        List<Name> names = new List<Name>();

        [ContextMenu("Init")]
        void Init()
        {
            Initialize(true);
        }

        void Initialize(bool refresh = false)
        {
            if (refresh)
            {
                initialized = false;
                names.Clear();
            }

            if (initialized && !Application.isEditor)
                return;

            names.Clear();

            foreach (var t in textSources)
            {
                StringReader rd = new StringReader(t.text);

                while (true)
                {
                    try
                    {
                        string line = rd.ReadLine();
                        string[] chunks = line.Split(',');
                        string n = chunks[0];
                        if (n.ToLower() == "name")
                            continue;

                        Name name = new Name(n);

                        for (int i = 1; i < chunks.Length; i++)
                        {
                            name.tags.Add(chunks[i].ToLower());
                        }

                        names.Add(name);

                    }
                    catch
                    {
                        break;
                    }
                }

            }


            initialized = true;
        }

        public string Get(params string[] tags)
        {
            Initialize();


            IEnumerable<Name> pool = names.AsEnumerable();

            for (int i = 0; i < tags.Length; i++)
            {
                string tag = tags[i].ToLower();

                if (i == 0)
                    pool = names.Where(x => x.tags.Contains(tag));
                else
                    pool = pool.Where(x => x.tags.Contains(tag));
            }

            var result = pool.Skip(Random.Range(0, pool.Count())).Take(1).FirstOrDefault();
            if (result == null)
                return "";

            return result.name;
        }


    }
}