using C4IT.DataHistoryProvider;
using C4IT.FASD.Base;
using C4IT.Logging;
using C4IT.XML;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Net.Http.Headers;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using static C4IT.Logging.cLogManager;

namespace F4SDwebService.Controllers
{
    public class LogonController : ApiController
    {
        [Route("api/Logon/GetUserIdByAccount")]
        public async Task<IHttpActionResult> GetUserIdByAccount(string Account, string Domain)
        {
            MethodBase CM = null; if (cLogManager.DefaultLogger.IsDebug) { CM = MethodBase.GetCurrentMethod(); LogMethodBegin(CM); }

            var requestInfo = new cF4sdWebRequestInfo("SearchDefault", (Domain ?? "") + ":" + (Account ?? ""));
            if (cPerformanceLogger.IsActive && requestInfo != null) { cPerformanceLogger.LogPerformanceStart(0, requestInfo.requestName, requestInfo.id, requestInfo.created); }

            var apiError = 0;

            try
            {
                var res = await WebApiApplication.Collector.GetUserIdFromAccountAsync(Account, Domain, requestInfo, 1, CancellationToken.None);
                if (res != null)
                    return Ok((Guid)res);
                return Ok(Guid.Empty);
            }
            catch (Exception E)
            {
                apiError = E.HResult;
                LogException(E);
            }
            finally
            {
                if (WebApiApplication.Debug_apiTiming) WebApiApplication.SaveApiTimingEntry(requestInfo.requestName, requestInfo.id, requestInfo.created, apiError);
                if (cPerformanceLogger.IsActive && requestInfo != null) { cPerformanceLogger.LogPerformanceEnd(0, requestInfo.requestName, requestInfo.id, requestInfo.created, requestInfo.created, ErrorCode: apiError); }
                if (CM != null) LogMethodEnd(CM);
            }

            return NotFound();
        }

        [Route("api/Logon/Logon")]
        [HttpGet]
        [Authorize]
        public async Task<IHttpActionResult> WinLogon(string lang = null)
        {
            MethodBase CM = null; if (cLogManager.DefaultLogger.IsDebug) { CM = MethodBase.GetCurrentMethod(); LogMethodBegin(CM); }

            var _id = HttpContext.Current?.User?.Identity;
            var requestInfo = new cF4sdWebRequestInfo("RegisterExternalToken", _id == null ? _id.Name : "unknown user");
            if (cPerformanceLogger.IsActive && requestInfo != null) { cPerformanceLogger.LogPerformanceStart(0, requestInfo.requestName, requestInfo.id, requestInfo.created); }

            var apiError = 0;

            try
            {
                LogEntry($"WinLogon with language: {lang}", LogLevels.Debug);
                if (WebApiApplication.Collector == null)
                    return NotFound();

                try
                {
                    var _regBase = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
                    var _regKey = _regBase.OpenSubKey("SOFTWARE\\Consulting4IT GmbH\\First Aid Service Desk\\Cockpit", false);
                    if (_regKey != null && int.TryParse(_regKey.GetValue("DebugNoAuthentication", 0).ToString(), out var _regFlag))
                    {
                        if (_regFlag > 0)
                            return Unauthorized();
                    }
                }
                catch { }
                if (_id == null)
                    return new System.Web.Http.Results.UnauthorizedResult(new List<AuthenticationHeaderValue>() { new AuthenticationHeaderValue("NTLM"), new AuthenticationHeaderValue("Negotiate") }, this);

                if (!string.IsNullOrEmpty(lang))
                {
                    try
                    {
                        lang = CultureInfo.GetCultureInfoByIetfLanguageTag(lang).IetfLanguageTag;
                    }
                    catch { }
                }

                var UserInfo = await WebApiApplication.Collector.GetWinUserInfoAsync(_id, lang, false, new CancellationTokenSource(18000).Token, requestInfo, 1);

                if (UserInfo == null)
                {
                    return new System.Web.Http.Results.UnauthorizedResult(new List<AuthenticationHeaderValue>() { new AuthenticationHeaderValue("NTLM"), new AuthenticationHeaderValue("Negotiate") }, this);
                }

                LogEntry($"Successfull WinLogon with language: {lang}", LogLevels.Debug);

                return Ok(UserInfo);
            }
            catch (Exception E)
            {
                apiError = E.HResult;
                LogException(E);
            }
            finally
            {
                if (WebApiApplication.Debug_apiTiming) WebApiApplication.SaveApiTimingEntry(requestInfo.requestName, requestInfo.id, requestInfo.created, apiError);
                if (cPerformanceLogger.IsActive && requestInfo != null) { cPerformanceLogger.LogPerformanceEnd(0, requestInfo.requestName, requestInfo.id, requestInfo.created, requestInfo.created, ErrorCode: apiError); }
                if (CM != null) LogMethodEnd(CM);
            }

            return NotFound();
        }

        [Route("api/Logon/RegisterExternalToken")]
        [HttpPost]
        public async Task<IHttpActionResult> RegisterExternalToken(cF4SDTokenRegistration TokenRegistration)
        {
            MethodBase CM = null; if (cLogManager.DefaultLogger.IsDebug) { CM = MethodBase.GetCurrentMethod(); LogMethodBegin(CM); }

            var requestInfo = new cF4sdWebRequestInfo("RegisterExternalToken", TokenRegistration.UserId.ToString() + "_" + TokenRegistration.TokenType.ToString(), cAuthentication.GetUserInfo(ActionContext));
            if (cPerformanceLogger.IsActive && requestInfo != null) { cPerformanceLogger.LogPerformanceStart(0, requestInfo.requestName, requestInfo.id, requestInfo.created); }

            var apiError = 0;

            try
            {
                var _res = await WebApiApplication.Collector.ValidateTokenAsync(TokenRegistration, requestInfo, 1, new CancellationTokenSource().Token);

                if (_res?.ValidLogonsUntil != null && _res.ValidLogonsUntil.Count > 0)
                {
                    _res.ChangeUserInfo(requestInfo.userInfo);
                    var _token = WebApiApplication.Collector.GenerateJsonWebToken(requestInfo.userInfo);
                    _res.Token = _token;

                    if (cLogManager.DefaultLogger.IsDebug)
                    {
                        var _msg = Newtonsoft.Json.JsonConvert.SerializeObject(_res, Newtonsoft.Json.Formatting.Indented);
                        var _lstMsg = new List<string>()
                        {
                            $"RegisterExternalToken result for user {TokenRegistration.Name} and token type {TokenRegistration.TokenType.ToString()}",
                            _msg
                        };
                        cLogManager.DefaultLogger.LogList(LogLevels.Debug, _lstMsg);
                    }

                    return Ok(_res);
                }
            }
            catch (Exception E)
            {
                apiError = E.HResult;
                LogException(E);
            }
            finally
            {
                if (WebApiApplication.Debug_apiTiming) WebApiApplication.SaveApiTimingEntry(requestInfo.requestName, requestInfo.id, requestInfo.created, apiError);
                if (cPerformanceLogger.IsActive && requestInfo != null) { cPerformanceLogger.LogPerformanceEnd(0, requestInfo.requestName, requestInfo.id, requestInfo.created, requestInfo.created, ErrorCode: apiError); }
                if (CM != null) LogMethodEnd(CM);
            }

            return NotFound();
        }

        [Route("api/Logon/GetAdditionalUserInfo")]
        [HttpGet]
        public async Task<IHttpActionResult> GetAdditionalUserInfo(string AccountType)
        {
            MethodBase CM = null; if (cLogManager.DefaultLogger.IsDebug) { CM = MethodBase.GetCurrentMethod(); LogMethodBegin(CM); }

            var _ui = cAuthentication.GetUserInfo(ActionContext);
            var requestInfo = new cF4sdWebRequestInfo("GetAdditionalUserInfo", AccountType + ((_ui?.Id is null) ? "" : "_" + _ui.Id.ToString()), _ui);
            if (cPerformanceLogger.IsActive && requestInfo != null) { cPerformanceLogger.LogPerformanceStart(0, requestInfo.requestName, requestInfo.id, requestInfo.created); }

            var apiError = 0;

            try
            {


                var _accountType = cXmlParser.GetEnumFromString(AccountType, enumAdditionalAuthentication.unknown);
                if (_accountType == enumAdditionalAuthentication.unknown)
                    return NotFound();

                var _retVal = await WebApiApplication.Collector.GetAdditionalUserInfo(_accountType, requestInfo, 1, CancellationToken.None);

                if (_retVal != null)
                    return Ok(_retVal);

                apiError = (int)HttpStatusCode.NotFound;
            }
            catch (Exception E)
            {
                apiError = E.HResult;
                LogException(E);
            }
            finally
            {
                if (cPerformanceLogger.IsActive && requestInfo != null) { cPerformanceLogger.LogPerformanceEnd(0, requestInfo.requestName, requestInfo.id, requestInfo.created, requestInfo.created, ErrorCode: apiError); }
                if (WebApiApplication.Debug_apiTiming) WebApiApplication.SaveApiTimingEntry(requestInfo.requestName, requestInfo.id, requestInfo.created, apiError);
                if (CM != null) LogMethodEnd(CM);
            }

            return NotFound();
        }
    }
}