using RobotClientWpf.Utilities;
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;

namespace RobotClientWpf.Views
{
    /// <summary>
    /// Interaction logic for ConfigView.xaml
    /// </summary>
    public partial class ConfigView : UserControl
    {
        private static readonly NLog.Logger log = NLog.LogManager.GetCurrentClassLogger();
        private ChallengeFactory? challenge;

        public ConfigView()
        {
            InitializeComponent();
        }

        public void SetChallengeFactory(ChallengeFactory challenge)
        {
            this.challenge = challenge;
        }

        private void btnApplyConfiguration_Click(object sender, RoutedEventArgs e)
        {
            List<TextBox> splitFlapTextboxes = new List<TextBox>() { tbSf1, tbSf2, tbSf3, tbSf4 };
            int setupIdCounter = 0;  // counting setup ID from 0
            foreach (var textbox in splitFlapTextboxes)
            {
                this.GetHwIdFromTbAndSendMqtt(textbox, setupIdCounter++);
                UIAccessHelpers.SetTextboxText(textbox, "");
            }
        }


        private void GetHwIdFromTbAndSendMqtt(TextBox tb, int id)
        {
            if(challenge != null)
            {
                string text = UIAccessHelpers.GetTextboxText(tb);
                // if nothing is in the textbox
                if (String.IsNullOrEmpty(text))
                {
                    return;
                }

                int hwId;
                if(int.TryParse(text, out hwId) == false)
                {
                    log.Warn($"Failed to parse HardwareID={text} given for Splitflap id={id}");
                    return;
                }
                    
                this.challenge.RobotStationary.SplitFlap.ConfigureSplitflap(id, hwId);
            }
            else
            {
                log.Error("challenge object is null");
            }
        }

        private void btnStartCalibration_Click(object sender, RoutedEventArgs e)
        {
            this.challenge?.RobotMobile.LineSensor.StartCalibration(true);
        }

        private void btnEndCalibration_Click(object sender, RoutedEventArgs e)
        {
            this.challenge?.RobotMobile.LineSensor.StartCalibration(false);
        }

        private void btnGetCalibrationData_Click(object sender, RoutedEventArgs e)
        {
            this.challenge?.RobotMobile.LineSensor.GetCalibrationData();
        }
    }
}
