using FLY.OBJComponents.IService;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows.Threading;

namespace FLY.OBJComponents.Client
{
    public class SetPLCUpdatePlan:IDisposable
    {
        IPLCProxySystemService PLCos;
        long planid;
        DispatcherTimer timer;
        string objname;
        IEnumerable<string> propertynames;

        public SetPLCUpdatePlan(IPLCProxySystemService plsos, INotifyPropertyChanged obj, IEnumerable<string> propertynames)
        {
            PLCos = plsos;

            this.propertynames = propertynames;
            this.objname = PLCos.ObjNames.First((kv) => kv.Value == obj).Key;

            planid = DateTime.Now.Ticks;
            timer = new DispatcherTimer()
            {
                Interval = TimeSpan.FromSeconds(2)
            };
            timer.Tick += (s, e) => {
                if (PLCos.IsConnectedWithPLC)
                {
                    PLCos.FeedPlan(planid);
                }
                else
                {
                    timer.IsEnabled = false;
                }
            };
            Misc.BindingOperations.SetBinding(PLCos, "IsConnectedWithPLC", () => {
                if (PLCos.IsConnectedWithPLC)
                {
                    //重新注册更新计划
                    PLCos.SetPlan(objname, propertynames, planid);
                    timer.IsEnabled = true;
                }
                else
                {
                    timer.IsEnabled = false;
                }
            });
        }

        public void Dispose()
        {
            timer.Stop();
            
        }
    }
}
