#pragma warning disable CS8019

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Web;

#if !NET8
using System.Web.Security;
#endif

using System.IO;
using System.Net.Mail;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;

#pragma warning restore CS8019

using Fab2ApprovalSystem.Models;

namespace Fab2ApprovalSystem.Misc;

public static class Functions {
    /// <summary>
    /// Writes to the Application Event Log and sends an email notification if appropriate
    /// </summary>

    public static void WriteEvent(AppSettings? appSettings, string logtext, EventLogEntryType eventType) {
#if !NET8
        EmailNotification? en = appSettings is null ? null : new EmailNotification(appSettings);
#endif
        EventLog ev = new("Application");
        ev.Source = "Fab Approval System";

        try {
            // Write to the Event Log
            ev.WriteEntry(logtext, eventType);

            // Send an email notification if appropriate
            // Don't attempt to send an email if the error is pertaining to an email problem
            if (!logtext.Contains("SendEmailNotification()")) {
                // Only send email notifications for Error and Warning level events
#if !NET8
                if (appSettings is not null && eventType == System.Diagnostics.EventLogEntryType.Error)
                    en.SendNotificationEmailToAdmin(ev.Source + " - Error Notification", logtext, MailPriority.High);
#endif
            }
        } catch {
        } finally {
            ev = null;
        }
    }

    public static void CopyAttachments(AppSettings appSettings, int oldECNNumber, int newECNNumber) {
        // The Name of the Upload component is "files"
        string oldFolderPath = appSettings.AttachmentFolder + "ECN\\" + oldECNNumber.ToString();
        string newFolderPath = appSettings.AttachmentFolder + "ECN\\" + newECNNumber.ToString();

        DirectoryInfo newdi = new(newFolderPath);

        if (!newdi.Exists)
            newdi.Create();

        FileInfo[] existingFiles = new DirectoryInfo(oldFolderPath).GetFiles();
        foreach (FileInfo file in existingFiles) {
            if (!file.Name.Contains("ECNApprovalLog_" + oldECNNumber.ToString()) && !file.Name.Contains("ECNForm_" + oldECNNumber.ToString()))
                file.CopyTo(Path.Combine(newFolderPath, file.Name));
        }
    }

    public static bool NA_ADAuthenticate(AppSettings appSettings, string userID, string pwd) {
        string naContainer = appSettings.NAContainer;
        string naDomain = appSettings.NADomain;
        try {
            PrincipalContext contextUser = new(ContextType.Domain,
                                       naDomain,
                                        naContainer,
                                       ContextOptions.Negotiate, userID, pwd);

            UserPrincipal up = UserPrincipal.FindByIdentity(contextUser, userID);
            if (null == up)
                return false;
            else
                return true;
        } catch {
            return false;
        }
    }

    public static bool IFX_ADAuthenticate(AppSettings appSettings, string userID, string pwd) {
        string container = appSettings.IFXContainer;
        string domain = appSettings.IFXDomain;
        try {
            PrincipalContext contextUser = new(ContextType.Domain,
                                       domain,
                                        container,
                                       ContextOptions.Negotiate, userID, pwd);

            UserPrincipal up = UserPrincipal.FindByIdentity(contextUser, userID);
            if (null == up)
                return false;
            else
                return true;
        } catch {
            return false;
        }
    }

    public static string CASectionMapper(GlobalVars.CASection casection) {
        switch (casection) {
            case GlobalVars.CASection.Main:
                return "Main";

            case GlobalVars.CASection.D1:
                return "D1";

            case GlobalVars.CASection.D2:
                return "D2";

            case GlobalVars.CASection.D3:
                return "D3";

            case GlobalVars.CASection.D4:
                return "D4";

            case GlobalVars.CASection.D5:
                return "D5";

            case GlobalVars.CASection.D6:
                return "D6";

            case GlobalVars.CASection.D7:
                return "D7";

            case GlobalVars.CASection.D8:
                return "D8";
            case GlobalVars.CASection.CF: // CA Findings 
                return "CF";
        }

        return "";
    }

    public static string DocumentTypeMapper(GlobalVars.DocumentType docType) {
        switch (docType) {
            case GlobalVars.DocumentType.Audit:
                return "Audit";
            case GlobalVars.DocumentType.ChangeControl:
                return "ChangeControl";
            case GlobalVars.DocumentType.CorrectiveAction:
                return "CorrectiveAction";
            case GlobalVars.DocumentType.ECN:
                return "ECN";
            case GlobalVars.DocumentType.EECN:
                return "EECN";
            case GlobalVars.DocumentType.LotDisposition:
                return "LotDisposition";
            case GlobalVars.DocumentType.MRB:
                return "MRB";
            case GlobalVars.DocumentType.TECNCancelledExpired:
                return "TECNCancelledExpired";
        }

        return "";
    }

    /// <summary>
    /// Converts the CA No to the C00000 format
    /// </summary>

    public static string ReturnCANoStringFormat(int caNo) {
        string caNoString = "";
        if (caNo == 0)
            return "";
        caNoString = "C" + caNo.ToString().PadLeft(5, '0');
        return caNoString;
    }

    public static string ReturnAuditNoStringFormat(int auditNo) {
        string auditNoString = "";
        if (auditNo == 0)
            return "";
        auditNoString = "A" + auditNo.ToString().PadLeft(5, '0');
        return auditNoString;
    }

    public static string ReturnPartsRequestNoStringFormat(int PRNumber) {
        if (PRNumber == 0)
            return "";
        return string.Format("PR{0:000000}", PRNumber);
    }
}