using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;

namespace Valg.EVA.Skanning.JobManagement.Startup.MainWindow
{
    public partial class MainWindow : IMainWindow
    {
        [DllImport("user32.dll")]
        private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
        [DllImport("user32.dll")]
        private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);

        private readonly IMainWindowViewModel viewModel;
        private bool isElectionConfigInstalled;

        public MainWindow(IMainWindowViewModel viewModel)
        {
            InitializeComponent();

            this.viewModel = viewModel;
            DataContext = viewModel;
        }

        public void ShowWindow(bool isKioskMode)
        {
            Show();
            if (isElectionConfigInstalled)
            {
                viewModel.Login();
            }
            else
            {
                viewModel.ShowElectionConfigMissingWindow();
            }

            if (isKioskMode)
            {
                HideMinimizeButton();
            }
        }

        private void HideMinimizeButton()
        {
            var hwnd = new WindowInteropHelper(this).Handle;
            Tools.WindowExtensions.HideMinimizeButton(hwnd);
        }

        public void Initialize(bool electionConfigIsInstalled)
        {
            isElectionConfigInstalled = electionConfigIsInstalled;
            viewModel.Initialize(electionConfigIsInstalled);
        }


        protected override void OnPreviewKeyDown(KeyEventArgs e)
        {
            if (e.Key == Key.F5)
                ((MainWindowViewModel)DataContext).RefreshCommand.Execute(null);
        }

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            try
            {
                Application.Current.Shutdown();
            }
            catch (Exception )
            {
                
            }
            
        }
    }
}
