﻿// Copyright (c) 2018 Nikolay Zahariev <zahasoft.com>. Licensed under the MIT License.

namespace Zahasoft.Clojar.Desktop
{
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Input;

    public partial class MainWindow : Window
    {
        readonly ClojureCompiler compiler = new ClojureCompiler();

        public MainWindow()
        {
            InitializeComponent();
        }

        async void MainWindow_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.Key)
            {
                case Key.F4:
                    ClearOutputBlock();
                    break;
                case Key.F5:
                    await ExecuteCode();
                    break;
                case Key.F6:
                    GoToHomePage();
                    break;
                case Key.F7:
                    GoToLastPage();
                    break;
                case Key.F8:
                    GoToNextPage();
                    break;
            }
        }

        async void Button_Click(object sender, RoutedEventArgs e)
        {
            switch ((sender as Button).Name)
            {
                case "ClearButton":
                    ClearOutputBlock();
                    break;
                case "RunButton":
                    await ExecuteCode();
                    break;
                case "HomeButton":
                    GoToHomePage();
                    break;
                case "BackButton":
                    GoToLastPage();
                    break;
                case "NextButton":
                    GoToNextPage();
                    break;
            }
        }

        void ClearOutputBlock()
        {
            OutputTextBlock.Text = "";
        }

        async Task ExecuteCode()
        {
            CompilationResult result = await compiler.CompileAsync(new ClojureExpression(InputTextBox.Text));
            OutputTextBlock.Text = string.Format("{0}\n{1}", OutputTextBlock.Text, result.Value);
        }

        void GoToHomePage()
        {
            WebBrowser.Navigate("http://clojure.org/");
        }

        void GoToLastPage()
        {
            if (WebBrowser.CanGoBack)
            {
                WebBrowser.GoBack();
            }
        }

        void GoToNextPage()
        {
            if (WebBrowser.CanGoForward)
            {
                WebBrowser.GoForward();
            }
        }
    }
}
