using System.Linq;
using System.Windows.Controls;
using System.Windows.Documents;
using C1.Silverlight.RichTextBox.Documents;
using C1.Silverlight.SpellChecker;

namespace CustomSpellCheckerMenu
{
    public partial class MainPage : UserControl
    {
        private SpellCheckerMenu spellCheckerMenu;

        public MainPage()
        {
            InitializeComponent();

            rtb.Text = @"Some facts about Mark Twain (spelling errors intentional ;-)

A steambat pilot neded a vast knowldege of the ever-chaging river to be able to stop at any of the hundreds of ports and wood-lots along the river banks. Twain meticulosly studied 2,000 miles (3,200 km) of the Mississipi for more than two years before he received his steamboat pilot license in 1859.

While training, Samuel covinced his younger brother Henry to work with him. Heny was killed on June 21, 1858, when the steamboat he was working on, the Pennsylvania, exploded. Twain had foreseen this death in a detailed dream a month earlier, [13] which inspired his interest in parasychology; he was an early member of the Society for Psychical Research.[14] Twain was guilt-strcken over his brother's death and held himself responsible for the rest of his life. However, he continued to work on the river and served as a river pilot until the American Civil War broke out in 1861 and traffic along the Mississipi was curtaled.

Missouri was a slave state and considered by many to be part of the South, and was represented in both the Confederate and Federal governments during the Civil War. When the war began, Twain and his friends formed a Confederate militia (depcted in an 1885 short story, ""The Private History of a Campaign That Failed""), which drilled for only two weeks before disbanding.[15] Twain joinded his brother, Orion, who had been apointed secretary to the teritorial govenor of Nevada, James W. Nye, and headed west.
 
Twain then traveled to San Francisco, California, where he comtinued as a journalist and began lecturing. He met other writers such as Bret Harte, Artemus Ward and Dan DeQuille. An assignment in Hawaii became the basis for his first lectures.[18] In 1867, a local newspaper funded a trip to the Mediterrannean. During his tohr of Europe and the Midddle East, he wrote a popular colection of travel letters wich were compled as The Inocents Abroad in 1869.";

            var spellChecker = new C1SpellChecker();
            rtb.SpellChecker = spellChecker;
            spellChecker.MainDictionary.LoadAsync("c1spell_en-us.dct");

            spellCheckerMenu = new SpellCheckerMenu(rtb);
            var enabled = C1.Silverlight.Clipboard.GetTextData();
        }

        private void richTB_MouseRightButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            // if the current selection is empty, try to get the word under the current cursor position
            C1TextRange wordRange = rtb.Selection;
            if (string.IsNullOrEmpty(wordRange.Text))
            {
                C1TextPointer pointer = rtb.GetPositionFromPoint(e.GetPosition(rtb));
                wordRange = pointer.GetWord();
            }

            // update the spell checker menu using the current selection/word
            spellCheckerMenu.UpdateSuggestions(wordRange);

            // show the context menu           
            spellCheckerMenu.Show(null, e.GetPosition(this));
            e.Handled = true;
        }
    }

    public static class C1TextPointerExtension
    {
        /// <summary>
        /// Returns the word corresponding to the current cursor position
        /// </summary>
        /// <param name="pointer">The pointer in the current cursor position</param>
        /// <returns>The word corresponding to the current cursor position</returns>
        public static C1TextRange GetWord(this C1TextPointer pointer)
        {
            var previousStart = new[] { pointer }.Concat(pointer.Enumerate(LogicalDirection.Backward)).FirstOrDefault(p => p.IsWordStart);
            var previousEnd = pointer.Enumerate(LogicalDirection.Backward).FirstOrDefault(p => p.IsWordEnd);

            var selectWord = previousEnd == null || previousStart >= previousEnd;
            var start = selectWord ? previousStart ?? pointer : previousEnd;
            var end = start.Enumerate(LogicalDirection.Forward).FirstOrDefault(p => selectWord ? p.IsWordEnd : p.IsWordStart) ?? pointer;
            return new C1TextRange(start, end);
        }
    }
}
