using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace ZionVault.Importers
{
    public class Csv
    {
        private List<string> headers;

        private List<List<string>> content;

        private List<List<string>> all;

        public List<string> Headers { get => headers ?? new List<string>(); }
        public List<List<string>> Content
        {
            get
            {
                if (all != null)
                    return all;

                all = new List<List<string>>();

                content.ForEach(line =>
                {
                    List<string> l = new List<string>();

                    line.ForEach(word => l.Add(word));

                    all.Add(l);
                });

                return all;
            }
        }

        public Csv(string path, char separator, bool haveheaders = false)
        {
            int index = 0;
            var lines = System.IO.File.ReadLines(path);
            content = new List<List<string>>();
            foreach (string line in lines)
            {
                index++;
                if (index == 1 && haveheaders)
                {
                    headers = line.ToUpperInvariant().Split(separator).ToList();
                    continue;
                }
                content.Add(line.Split(separator).ToList());
            }
        }

        public int GetHeaderIndex(string value)
        {
            int index;
            if (int.TryParse(value, out index))
                return index;
            var a = headers.IndexOf(value.ToUpperInvariant());
            var b = headers.IndexOf(value.ToUpper());

            return headers.IndexOf(value.ToUpperInvariant());
        }

        public List<List<string>> filter(Param.Csv param, string removeChars)
        {
            int index = GetHeaderIndex(param.Header);

            removeChars = removeChars != null ? removeChars : @"";

            return (from item in Content
                    where Regex.Replace(item[index].Trim(), removeChars, string.Empty) == Regex.Replace(param.Value.Trim(), removeChars, string.Empty)
                    select item).ToList();
        }

        public List<List<string>> find(Param.Csv param, string removeChars = @"")
        {
            return filter(param, removeChars);
        }

        public List<List<string>> find(List<Param.Csv> ListOfParams, string removeChars = @"")
        {
            List<List<string>> list = new List<List<string>>();

            foreach (Param.Csv param in ListOfParams)
            {
                filter(param, removeChars).ForEach(f =>
                {
                    list.Add(f);
                });
            }

            return list;
        }
    }
}
