using ControlzEx.Standard;
using MahApps.Metro.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace ZKuP
{
    /// <summary>
    /// Interaktionslogik für COMSelector.xaml
    /// </summary>
    public partial class COMSelector : MetroWindow
	{
        private List<string> COMList = new List<string>();

        public COMSelector()
        {
            InitializeComponent();

            COMList = Helper.GetCOMPorts();
            cbCOMList.ItemsSource = COMList;
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            if (cbCOMList.SelectedValue != null)
            {
                var match = Regex.Match(cbCOMList.SelectedValue.ToString(), @"COM\d+(?=\))");
                Settings.WriteSetting("COMPort", match.Value);
            }
            else Settings.WriteSetting("COMPort", "");

            this.Close();
        }

        private void cbCOMList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {            
            Helper.DataReceived += Helper_DataReceived;
            MessageBox.Show("Bitte jetzt den Leser testen:\n\nSchließen Sie diese Meldung und legen Sie anschließend eine Karte auf!\n\nWird nach dem Auflegen keine Meldung angezeigt, bitte anderen Port wählen", "Kartenleser testen", MessageBoxButton.OK, MessageBoxImage.Information);
            Helper.InitSerial(cbCOMList.SelectedValue.ToString());
        }

        private void Helper_DataReceived(object sender, string e)
        {
            if (e.Split('=')[0].Length == 19)
            {
                MessageBox.Show("Test des Kartenlesers erfolgreich!", "Erfolg", MessageBoxButton.OK, MessageBoxImage.Information);

                Helper.DataReceived -= Helper_DataReceived;
            }
        }
    }
}
