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

namespace AssetUpdate
{
    public class TextReader
    {
        public readonly List<string[]> contentLines = new List<string[]>();
        public readonly bool error;
        public readonly string name;
        public readonly string[] titles;
        public readonly string[] types;

        public TextReader(string path)
        {
            name = Path.GetFileNameWithoutExtension(path);
            var lines = File.ReadAllLines(path);
            if (lines.Length < 3)
            {
                error = true;
                Debug.LogError(string.Format("Excel text file at {0} has no valid data!", path));
            }
            else
            {
                titles = ReadLine(lines[0]);
                types = ReadLine(lines[1]);
                if (titles.Length == types.Length)
                {
                    for (var i = 2; i < lines.Length; i++)
                    {
                        var line = ReadLine(lines[i]);
                        if (line != null)
                        {
                            if (line.Length == titles.Length)
                            {
                                contentLines.Add(line);
                            }
                            else
                            {
                                error = true;
                                Debug.LogError(
                                    string.Format("Line {0} in file {1} has {2} elements, while the title has {3}!", i,
                                        path, titles.Length, line.Length));
                            }
                        }
                    }
                }
                else
                {
                    error = true;
                    Debug.LogError(
                        string.Format("File {0} has {1} elements in title, while {2} in type!", path, titles.Length,
                            types.Length));
                }
            }
        }

        private string[] ReadLine(string line)
        {
            return string.IsNullOrEmpty(line) ? null : line.Split('\t');
        }
    }
}