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, string objname, IEnumerable<string> propertynames)
        {
            PLCos = plsos;

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



            timer = new DispatcherTimer()//120s 内必须再次注册
            {
                Interval = TimeSpan.FromSeconds(60)
            };
            timer.Tick += (s, e) =>
            {
                if (planid != 0)
                {
                    PLCos.FeedPlan(planid);
                }
            };
            
            if(IsTimeToSetPlan())
            {
                PLCos.SetPlan(this.objname, this.propertynames, (asyncContext, retData) =>
                {
                    long planid = (long)retData;
                    this.planid = planid;
                    timer.Start();
                }, null);
            }
            if (PLCos is PLCProxySystemServiceClient) 
                PLCos.PropertyChanged += PLCos_PropertyChanged;
            
        }
        bool IsTimeToSetPlan() 
        {
            if (PLCos is PLCProxySystemServiceClient)
            {
                var _PLCos = PLCos as PLCProxySystemServiceClient;
                if (_PLCos.IsConnected)
                {
                    return true;
                }
                else {
                    return false;
                }
            }
            else {
                return true;
            }
        }
        private void PLCos_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == nameof(PLCProxySystemServiceClient.IsConnected))
            {
                var _PLCos = PLCos as PLCProxySystemServiceClient;
                if (_PLCos.IsConnected)
                {
                    PLCos.SetPlan(objname, propertynames, (asyncContext, retData) =>
                    {
                        long planid = (long)retData;
                        this.planid = planid;
                        timer.Start();
                    }, null);
                }
                else
                {
                    this.planid = 0;
                    timer.Stop();
                }
            }
        }

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

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