using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Ported.VisualBasic.FileIO;
namespace DFEngine.IO
{
///
/// Class that represents the contents of a Script file.
///
public class Script : IDisposable
{
///
/// The script's rows, sorted by group.
///
private readonly Dictionary> _rows;
///
/// Creates a new instance of the class.
///
/// The path of the file handle.
public Script(string path)
{
if (!File.Exists(path))
{
throw new FileNotFoundException("Could not find the file specified.", path);
}
_rows = new Dictionary>();
PopulateRows(path);
}
///
/// Safely obtains the rows associated with the specified group.
///
/// The group to obtain.
public List this[string group] => _rows.GetSafe(group);
///
/// Disposes the file handle.
///
public void Dispose()
{
// empty...
}
///
/// Populate's the script's rows with the contents from the file.
///
private void PopulateRows(string path)
{
using (var reader = new TextFieldParser(path))
{
reader.TrimWhiteSpace = true;
reader.CommentTokens = new[] { ";" };
reader.SetDelimiters(",", "\t", " ");
reader.HasFieldsEnclosedInQuotes = true;
while (!reader.EndOfData)
{
var row = reader.ReadFields();
if (row == null || row.Length <= 0)
{
continue;
}
var group = row[0];
if (group == "" || group.ToLower() == "#define" || group.ToLower() == "#enddefine")
{
continue;
}
if (group.ToLower() == "#include")
{
PopulateRows(row[1]);
continue;
}
row = row.Where(s => s != group && s != "").ToArray();
if (!_rows.ContainsKey(group))
{
_rows.Add(group, new List());
}
_rows[group].Add(new ScriptRow(row));
}
reader.Close();
}
}
}
}