﻿using Barsik.Core;
using GalaSoft.MvvmLight.Messaging;
using NLog;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;

namespace Barsik
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Messenger.Default.Register<int>(this, OnServersUpdated);
        }

        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            var server = serverListDataGrid.SelectedItem as ServerInfoViewModel;
            if (server != null)
            {
                var isPasswordCorrect = await server.Server.Rcon.CheckAuthenticationAsync();
                if (isPasswordCorrect)
                {
                    checkRconPasswordButton.Content = "OK";
                }
                else
                {
                    checkRconPasswordButton.Content = "ERROR";
                }
            }
        }

        private void OnServersUpdated(int value)
        {
            SortDataGrid(serverListDataGrid);
            SortDataGrid(playersDataGrid);
        }

        private void consoleTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            consoleTextBox.ScrollToEnd();
        }

        private void updateTimer_Tick(object sender, EventArgs e)
        {
            SortDataGrid(serverListDataGrid);
            SortDataGrid(playersDataGrid);
        }

        private static void SortDataGrid(DataGrid dataGrid)
        {
            var sortDescriptions = new SortDescriptionCollection();
            foreach (SortDescription sd in dataGrid.Items.SortDescriptions)
            {
                sortDescriptions.Add(sd);
            }
            dataGrid.Items.SortDescriptions.Clear();

            foreach (SortDescription sd in sortDescriptions)
            {
                dataGrid.Items.SortDescriptions.Add(sd);
            }
        }

        private void serverListDataGrid_TargetUpdated(object sender, System.Windows.Data.DataTransferEventArgs e)
        {
            //foreach (DataGridColumn col in serverListDataGrid.Columns)
            //{
            //    //if (col != nameColumn)
            //    {
            //        col.Width = 0;
            //        col.Width = DataGridLength.Auto;
            //    }
                

            //}
            //serverListDataGrid.UpdateLayout();
            //nameColumn.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
            //serverListDataGrid.UpdateLayout();
        }
    }
}
