using System;
using System.IO;
using System.Windows;
using System.Windows.Input;
using Machinations.FromFlash.machinations.model;

namespace Machinations
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        public MainWindow()
        {
            var graph = new MachinationsGraph();
            InitializeComponent();
            PaintingCanvas.Initialize(graph, ProgramControl.GraphControl, ProgramControl.ComponentsSettings);
            ProgramControl.Initialize(graph, PaintingCanvas);
            if (ProgramControl.Settings.AutoSave && File.Exists(MachnationsSettings.LastGraph))
            {
                ProgramControlUtils.OpenFile(true, MachnationsSettings.LastGraph,graph, ProgramControl, PaintingCanvas);
            }
            else
                ProgramControl.Reset();
            
        }

        private void OnKeyDown(object sender, KeyEventArgs e)
        {
            if (ProgramControl.Running)
                KeyDownRunning(e);
            else
                KeyDownEdit(e);
            //e.Handled = true;
        }

        private void KeyDownEdit(KeyEventArgs e)
        {
            if (e.Key == Key.Delete)
            {
                PaintingCanvas.Delete();
                return;
            }
            if (Keyboard.IsKeyDown(Key.LeftCtrl))
            {
                if (e.Key == Key.OemPlus || e.Key == Key.Add)
                {
                    PaintingCanvas.ScrollViewerHeight += 100;
                    PaintingCanvas.ScrollViewerWidth += 100;
                    //PaintingCanvas.ScrollViewer.UpdateLayout();
                    return;
                }
                if (e.Key == Key.Subtract || e.Key == Key.OemMinus)
                {
                    PaintingCanvas.ScrollViewerHeight -= 100;
                    PaintingCanvas.ScrollViewerWidth -= 100;
                    //PaintingCanvas.ScrollViewer.UpdateLayout();
                    return;
                }
            }
            
            if (ProgramControlUtils.IsFunctionKey(e.Key))
                ProgramControl.GraphControl.SetButton(e.Key);

        }

        private void KeyDownRunning(KeyEventArgs e)
        {
            if (e.Key == Key.Space)
            {
                if (ProgramControl.TimerTicking)
                {
                    ProgramControl.MySimulationControl.Stop();
                    ProgramControl.TimerTicking = false;
                }
                else
                {
                    ProgramControl.MySimulationControl.Start();
                    ProgramControl.TimerTicking = true;
                }
            }
            return;
        }
    }
}
