using CompControl.SapFrameworkConnector;
using Microsoft.Owin;
using Microsoft.Owin.Hosting;
using SAP.Middleware.Connector;
using System;
using System.ServiceProcess;

namespace CompControl.SapFrameworkConnector
{
    public partial class Service : ServiceBase
    {
        private static readonly log4net.ILog _log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private IDisposable _server = null;


        public Service()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            RfcTrace.DefaultTraceLevel = 3;
            RfcTrace.TraceDirectory = @"C:\Temp\CC\NCoLogs"; // Log-Dateien in diesem Ordner speichern
            _log.Debug("SAP NCo Logging aktiviert: " + RfcTrace.TraceDirectory);

            var config = new ConfigFileDestination();
            if (!RfcDestinationManager.IsDestinationConfigurationRegistered()) { RfcDestinationManager.RegisterDestinationConfiguration(config); }
            var dest = RfcDestinationManager.GetDestination(ConfigHelper.ActiveSapDestinationName); // Jetzt kannst du die Destination abrufen
            _log.Info("SAP Destination loaded: " + dest.Name);

            _server = WebApp.Start<Startup>(url: ConfigHelper.ThisWebApiServiceEndpoint);
            _log.Info($"Service started successfully at: {ConfigHelper.ThisWebApiServiceEndpoint}");
        }

        protected override void OnStop()
        {
            _log.Debug($"Service was stopped!");
        }

    }
}

public class ConfigFileDestination : IDestinationConfiguration
{
    private static readonly log4net.ILog _log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    public RfcConfigParameters GetParameters(string destinationName)
    {
        RfcConfigParameters parms = new RfcConfigParameters();
        parms.Add(RfcConfigParameters.AppServerHost, ConfigHelper.SapASHOST);
        parms.Add(RfcConfigParameters.SystemNumber, ConfigHelper.SapSYSNR);
        parms.Add(RfcConfigParameters.Client, ConfigHelper.SapCLIENT);
        parms.Add(RfcConfigParameters.User, ConfigHelper.SapDefaultUSER);
        parms.Add(RfcConfigParameters.Password, ConfigHelper.SapDefaultPASSWD);
        parms.Add(RfcConfigParameters.Language, ConfigHelper.SapLanguage);
        _log.Debug($"Destination registered => ASHOST={ConfigHelper.SapASHOST} | SYSNR={ConfigHelper.SapSYSNR} | CLIENT={ConfigHelper.SapCLIENT} | USER={ConfigHelper.SapDefaultUSER} | LANG={ConfigHelper.SapLanguage}");
        return parms;
    }

    public bool ChangeEventsSupported() => false;
    public event RfcDestinationManager.ConfigurationChangeHandler ConfigurationChanged;
}