﻿using ServiceFramework;
using ServiceFramework.Configuration;
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Win_Service_Client.Common;

namespace Win_Service_Client
{
    partial class UserDefinedService : ServiceBase
    {
        PluginManager PluginManager;
        ServicePluginSection ServiceSetting() => (ServicePluginSection)System.Configuration.ConfigurationManager.GetSection("service");
        List<IServicePluginBase> pluginList = new List<IServicePluginBase>();

        public UserDefinedService()
        {
            InitializeComponent();
            PluginManager = PluginManager.CreateInstance();
        }

        protected override void OnStart(string[] args)
        {
            var pluginSettings = ServiceSetting().PluginSettings.ToList<PluginSettingSection>();
            pluginList = (from pluginSetting in pluginSettings
                          join plugin in PluginManager.PluginCollection on pluginSetting.PluginName equals plugin.ServiceData.ServiceName
                          where pluginSetting.IsEnable
                          select plugin).ToList();
            if (pluginList.Count > 0)
            {
                foreach (var job in pluginList)
                {
                    var setting = ServiceSetting().PluginSettings.ToList<PluginSettingSection>().Single(a => a.PluginName == job.ServiceData.ServiceName);
                    ThreadPool.QueueUserWorkItem(callBack, new KeyValuePair<IServicePluginBase, PluginSettingSection>(job, setting));
                }
            }
        }

        private void callBack(object state)
        {
            while (true)
            {
                var job = (KeyValuePair<IServicePluginBase, PluginSettingSection>)state;
                job.Key.Start();
                Thread.Sleep(job.Value.Interval);
            }
        }

        protected override void OnStop()
        {
            if (pluginList != null)
            {
                pluginList.Clear();
            }
            // TODO: 在此处添加代码以执行停止服务所需的关闭操作。
        }
    }
}
