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=0;
        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;

            PLCos.PropertyChanged += PLCos_PropertyChanged;

            timer = new DispatcherTimer()//120s 内必须再次注册
            {
                Interval = TimeSpan.FromSeconds(60)
            };
            timer.Tick += (s, e) =>
            {
                if (planid != 0)
                {
                    PLCos.FeedPlan(planid);
                }
            };

            if (((PLCProxySystemServiceClient)PLCos).IsConnected)
            {
                PLCos.SetPlan( this.objname, this.propertynames, (planid, context) =>
                {
                    this.planid = planid;
                    timer.Start();
                }, null);
            }
        }

        private void PLCos_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "IsConnected")
            {
                if (((PLCProxySystemServiceClient)PLCos).IsConnected)
                {
                    PLCos.SetPlan(objname, propertynames, (planid, context) =>
                    {
                        this.planid = planid;
                        timer.Start();
                    }, null);
                }
                else
                {
                    this.planid = 0;
                    timer.Stop();
                }
            }
        }

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

            if(planid!=0)
                PLCos.RemovePlan(planid);
        }
    }
}
