using SWRIS.Events;
using SWRIS.Extensions;
using SWRIS.Models.ViewModel;
using SWRIS.Repository;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Controls;

namespace SWRIS.Pages.RealTime
{
    /// <summary>
    /// OneRopePage.xaml 的交互逻辑
    /// </summary>
    public partial class OneRopePage : Page
    {
        private readonly IRecordRepository _recordRepository;
        public OneRopeViewModel OneRopeView { get; set; }

        public OneRopePage()
        {
            InitializeComponent();
            Loaded += OneRopePage_Loaded;
            Unloaded += OneRopePage_Unloaded;
            _recordRepository = new RecordRepository();

            OneRopeView = new OneRopeViewModel
            {
                EquipmentData = App.DataCenter.Equipments[0],
                Records = _recordRepository.GetLastRecords().ToSimpleRecordDtos()
            };

            OneRopeView.Equipment = App.Config.Equipments.First(c => c.IpAddress == OneRopeView.EquipmentData.IpAddress);
            DataContext = OneRopeView;
            App.TcpServer.LiveStreamReceived += TcpServer_LiveStreamReceived;
        }

        private void OneRopePage_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            if (OneRopeView.EquipmentData.ChartSource != null)
            {
                chartLine.AddDataPoints(OneRopeView.EquipmentData.ChartSource);
            }
        }

        private void OneRopePage_Unloaded(object sender, System.Windows.RoutedEventArgs e)
        {
            OneRopeView.EquipmentData.ChartSource = chartLine.GetChartSource();
        }

        private async void TcpServer_LiveStreamReceived(object sender, LiveStreamReceivedEventArgs e)
        {
            if (e.IpAddress == OneRopeView.EquipmentData.IpAddress)
            {
                if (OneRopeView.EquipmentData.DetectionData?.DetectionNo == OneRopeView.EquipmentData.DetectionNo)
                {
                    OneRopeView.EquipmentData.ClearData();
                }
                await Task.Run(() =>
                {
                    chartLine.AddDataPoints((OneRopeView.EquipmentData.AbsolutePosition, e.LiveStream),OneRopeView.EquipmentData.InUseSensor);
                });
            }
        }

        private void AlarmDetail_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            DamagesDialog damagesDialog = new DamagesDialog(OneRopeView.EquipmentData.Alarms);
            damagesDialog.ShowDialog(true);
        }

        private void ParameterSetting_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            ParameterDialog parameterDialog = new ParameterDialog(OneRopeView.Equipment, OneRopeView.EquipmentData.ClientSocket);
            parameterDialog.ShowDialog(true);
        }
    }
}
