using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.IO;

using MVVM;

using sdkdef = YoseenPTZ.SDKDef;

using YoseenPTZ.ConfigDef;
using YoseenPTZ.CoreDef;
using YoseenPTZ.ResourceDef;

namespace YoseenPTZ.ViewDef
{
    public partial class DebugView : Window
    {
        #region single
        static DebugView __instance;
        public static void ShowView(DeviceView deviceView)
        {
            if (__instance == null)
            {
                __instance = new DebugView(deviceView);
                __instance.Owner = App.Instance.ShellView;
                __instance.Show();
            }
            else
            {
                __instance.Show();
            }
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            if (!_forceClose)
            {
                e.Cancel = true;
                this.Hide();
            }
            base.OnClosing(e);
        }

        bool _forceClose;
        public static void ForceClose()
        {
            if (__instance == null) return;
            __instance._forceClose = true;
            __instance.Close();
            __instance = null;
        }

        #endregion

        string _PTZ;

        readonly DeviceView _deviceView;
        DebugView(DeviceView deviceView)
        {
            MaterialDesignWindow.RegisterCommands(this);
            InitializeComponent();

            try
            {
                _PTZ = File.ReadAllText(AppStatic.Config + "\\PTZ.txt");
            }
            catch (Exception ex)
            {
                LogUtil.Error(ex.Message);
            }

            //
            _deviceView = deviceView;
            txtNote.Text = _PTZ;
        }

        bool hex_str2int(string s, ref int i)
        {
            bool b = Regex.IsMatch(s, "^[0-9a-fA-F]{8}$");
            if (!b) return false;
            i = Convert.ToInt32(s, 16);
            return true;
        }
        string hex_int2str(int i)
        {
            return i.ToString("x8");
        }

        private void btnExecute_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                int ret;
                string req = txtReq.Text;
                int reqInt = 0;
                if (!hex_str2int(req, ref reqInt)) return;

                txtResp.Text = "";
                int r = 0;
                ret = _deviceView.PTZW4R4(reqInt, ref r);
                if (0 > ret) return;

                txtResp.Text = hex_int2str(r);
            }
            catch (Exception ex)
            {
                LogUtil.Error(ex.Message);
            }
        }
    }
}
