using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

using miew.BitArray;
using miew.String;
using miew.Enumerable;
using miew.Debugging;
using miew.Tokenization;

using agree;

//using tldb;


#if false
		var pf = new PetFormatter(g.loadtray);

		//Console.WriteLine(pf.GetPetFormattedEdge(g.tm.type_dict["nom_relation"]));
		//return;
		//Console.WriteLine();
		//Console.WriteLine(pf.GetPetFormattedEdge(g.tm.type_dict["handle"]));

		using (StreamWriter sw1 = new StreamWriter(@"agree-fs-dump.txt"))
		using (StreamWriter sw2 = new StreamWriter(@"pet-fs-dump.txt"))
		{
			foreach (agree.Type t in pf.OrderByPet(g.tm.AllTypes.Where(tz => !tz.Name.StartsWith("glbtype"))))
			{
				sw1.WriteLine(pf.GetPetFormattedEdge(t));
				sw2.WriteLine(pf.pet_fs_dict[t.Name]);
			}
		}
		return;
#endif

public class PetFormatter
{
	static readonly String[] sc7 = { "\t\"", "\" ", "(", ")", "\t" };
	Dictionary<String, int> pet_sym_map;
	Tfs.MonospaceFormatter mf;
	public Dictionary<String, String> pet_fs_dict;

	public PetFormatter(Grammar g)
	{
		pet_sym_map = File.ReadAllLines("/programming/analytical-grammar/erg-funcs/pet-symbol-key.txt")
			.Select(s => s.Split(sc7, StringSplitOptions.RemoveEmptyEntries))
			.Where(rgs => rgs.Length == 3)
			.Select(rgs => new { id = int.Parse(rgs[0]), sym = rgs[1].Trim() })
			._GroupBy(r => r.sym, StringComparer.InvariantCultureIgnoreCase)
			.Select(gz => gz.ArgMin(r => r.id))
			.ToDictionary(r => r.sym, r => r.id, StringComparer.InvariantCultureIgnoreCase);

		//int max_id = pet_sym_map.Values.Max();

		mf = new Tfs.MonospaceFormatter(g.tm);

		mf.FeatureDisplayOrder = File.ReadAllText("/programming/analytical-grammar/erg-funcs/pet-feat-order.txt")
										.ToUpper()
										.Split()
										.Select(s => s.Trim())
										.Where(s => s != String.Empty)
										.Select(s => g.tm.feat_map[s].i_feat)
										.ToArray();

		String[] sc4 = { "\n(" };
		pet_fs_dict = File.ReadAllText("/programming/analytical-grammar/erg-funcs/fs-dump.txt")
				.Split(sc4, StringSplitOptions.RemoveEmptyEntries)
				.ToDictionary(s =>
				{
					String title = s.Lines().First();
					return title.Substring(title.IndexOf(')') + 2);
				}, s => "(" + s);
	}

	public IEnumerable<agree.Type> OrderByPet(IEnumerable<agree.Type> seq)
	{
		return seq.OrderBy(t => pet_sym_map[t.Name]);
	}

	public String GetPetFormattedEdge(agree.Type t)
	{
		return String.Format("({0}) ", pet_sym_map[t.Name].ToString()) + mf.FormatEdge(t.Expanded);
	}
};