using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Channels;

namespace MECF.Framework.Common.MultiProcess.ProcessCenter
{

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple, UseSynchronizationContext = false)]
    public class MultiProcessService : IMultiProcessService
    {
        public bool CanEnterProcessIdleNow(string sicMachineName, string pmName, string state, out string result)
        {
            return MULTIPROCESS.CanEnterProcessIdleNow(GetClientInformation(sicMachineName, pmName),sicMachineName, pmName, state, out result);
        }

        public bool CanEnterProcessNow(string sicMachineName, string pmName, string state, out string result)
        {
            
            return MULTIPROCESS.CanEnterProcessNow(GetClientInformation(sicMachineName, pmName),sicMachineName, pmName, state, out result);
        }

        public List<string> QueryAllProcessInformation()
        {
            return MULTIPROCESS.QueryAllProcessInformation();
        }

        public string QueryMyProcessInformation(string sicMachineName, string pmName)
        {
            return MULTIPROCESS.QueryMyProcessInformation(sicMachineName, pmName);
        }

        public bool UpdateChamberState(string sicMachineName, string pmName, string state, string heatbase)
        {
            return MULTIPROCESS.UpdateChamberState(GetClientInformation(sicMachineName, pmName), sicMachineName, pmName, state, heatbase);
        }

        private string GetClientInformation(string sicMachineName, string pmName)
        {
            //提供方法执行的上下文环境
            OperationContext context = OperationContext.Current;
            //获取传进的消息属性
            MessageProperties properties = context.IncomingMessageProperties;
            //获取消息发送的远程终结点IP和端口
            RemoteEndpointMessageProperty endpoint = properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;

            return $"{sicMachineName} {pmName}; {endpoint.Address}";
        }
    }
}
