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

namespace TAWordGameLib.Solvers.SolverC
{
    public class TrieLetters : List<TrieLetter>
    {

    }

    public class TrieLetter
    {
        public TrieLetter(char c = '^', TrieLetter parent = null)
        {
            Letter = char.ToUpper(c);
            Parent = parent;
            Children = new TrieLetters();
        }

        public char Letter { get; private set; }
        public TrieLetter Parent { get; private set; }
        public TrieLetters Children { get; private set; }

        public TrieLetter CreateChild(char c)
        {
            var child = new TrieLetter(c, this);
            Children.Add(child);
            return child;
        }

        public TrieLetter GetChild(char c, bool createIfNotExist = false)
        {
            var child = Children.FirstOrDefault(x => x.Letter == char.ToUpper(c));
            if (child != null) return child;
            return !createIfNotExist ? null : CreateChild(c);
        }

        public override string ToString()
        {
            string word = Letter.ToString();
            var me = Parent;
            while (me.Letter != '^')
            {
                word = me.Letter + word;
                me = me.Parent;
            }
            return word;
        }
    }
}
