using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using com.itac.mes.imsapi.domain;
using com.itac.mes.imsapi.transport;

namespace com.itac.mes.imsapi.client.dotnet
{
    public abstract class IMSApiDotNetBase : IDisposable
    {
        public const int IMSAPI_NOT_INITIALIZED=-10301, IMSAPI_INITIALIZED_ALREADY=-10302, IMSAPI_LOCATOR_INIT_FAILED=-10303, IMSAPI_LOOKUP_FAILED=-10304, IMSAPI_REMOTE_SERVER_CALL_FAILED=-10305;
        protected readonly Dictionary<string,string> properties=new Dictionary<string,string>(StringComparer.OrdinalIgnoreCase);
        protected IhapClient client;
        protected IMSApiServiceStub service;
        protected bool initialized;

        public virtual void setProperty(string key,string value){properties[key]=value;}
        protected string Prop(string key,string fallback=null){string v;return properties.TryGetValue(key,out v)?v:fallback;}
        public virtual int imsapiInit()
        {
            if(initialized)return IMSAPI_INITIALIZED_ALREADY;
            try
            {
                var o=new IhapClientOptions();
                o.AppId=Prop("itac.appid","IMSApiDotNet"); o.AppType=Prop("itac.apptype",null);
                string direct=Prop("itac.artes.ihap.serviceurl",null); if(!string.IsNullOrWhiteSpace(direct))o.ServiceUrl=direct;
                string nodes=Prop("itac.artes.clusternodes",null);
                if(!string.IsNullOrWhiteSpace(nodes))foreach(var n in nodes.Split(new[]{',',';',' '},StringSplitOptions.RemoveEmptyEntries))o.ClusterNodes.Add(n.Trim());
                if(double.TryParse(Prop("itac.artes.connection.timeout",null),NumberStyles.Any,CultureInfo.InvariantCulture,out var ms))o.Timeout=TimeSpan.FromMilliseconds(ms);
                o.CompressRequests=IsTrue(Prop("itac.artes.ihap.compressed","false"));
                o.EnableFailover=!string.Equals(Prop("itac.artes.ihas.failover","true"),"false",StringComparison.OrdinalIgnoreCase);
                o.IgnoreNetworkPrefix=IsTrue(Prop("itac.artes.ihas.ignorenetworkprefix","false"));
                string ph=Prop("itac.artes.ihap.locator.httpProxyHost",null); string pp=Prop("itac.artes.ihap.locator.httpProxyPort",null);
                if(!string.IsNullOrWhiteSpace(ph)){int p=8080;int.TryParse(pp,out p);o.Proxy=new WebProxy(ph,p);}
                client=new IhapClient(o); service=new IMSApiServiceStub(client); initialized=true; return 0;
            }
            catch{return IMSAPI_LOCATOR_INIT_FAILED;}
        }
        public virtual int imsapiShutdown(){if(!initialized)return IMSAPI_NOT_INITIALIZED;Dispose();return 0;}
        public abstract int imsapiGetLibraryVersion(ref string libraryVersion);
        protected static bool IsTrue(string v)=>string.Equals(v,"1")||string.Equals(v,"true",StringComparison.OrdinalIgnoreCase)||string.Equals(v,"yes",StringComparison.OrdinalIgnoreCase);
        protected int Guard(){return initialized?0:IMSAPI_NOT_INITIALIZED;}
        public virtual void Dispose(){service=null;if(client!=null){client.Dispose();client=null;}initialized=false;}
    }
}
