using ILogger = Microsoft.Extensions.Logging.ILogger;
using LoggerFactory = Microsoft.Extensions.Logging.LoggerFactory;
using ms_namingservice.Database;
using ms_namingservice.Objects;
using ms_namingservice.Objects.SavedData;

namespace ms_namingservice.Mapping.ValuesMapping;

/// <summary>
/// Class handling with method for subcategory mapping.
/// </summary>
public class SubcategoryMapping
{
    /// <summary>
    /// Represents the logger instance for this class.
    /// </summary>
    private static ILogger Logger = Logging.LoggerFactory.CreateLogger<SubcategoryMapping>();
    
    /// <summary>
    /// Gets the subcategory for a given framework.
    /// </summary>
    /// <param name="framework">The framework to get the subcategory for.</param>
    /// <returns>The subcategory for the given framework, or null if the framework is not supported.</returns>
    public static async Task<string> GetSubcategory(string framework)
    {
        // Check if the framework is MITRE.
        if (framework.Equals(Const.Mitre))
        {
            try
            {
                // Check, if the subcategory can be recognised from the tags.
                if (InputData.Input.Tags[1].Equals("null") || InputData.Input.Tags[1] == null)
                {
                    return "Other";
                }
                
                // Get the short subcategory for the second tag from the database.
                string subcategoryShort = await RulesQuery.GetSubcategoryShort(InputData.Input.Tags[1], framework);

                // If the short subcategory is not found in the database, set it to Other.
                if (subcategoryShort == null)
                {
                    subcategoryShort = "Other";
                }
                
                // Get the long subcategory for the short subcategory using the method in this class
                return await GetLongSubcategory(subcategoryShort);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex.Message); //Log error
            }
        }

        // ENISA does not have subcategories
        return null;
    }

    /// <summary>
    /// Gets the long name for a given subcategory.
    /// </summary>
    /// <param name="subcategory">The short name of the subcategory.</param>
    /// <returns>The long name of the subcategory.</returns>
    private static async Task<string> GetLongSubcategory(string subcategory)
    {
        //Mapping short values of the subcategory to the long values of the subcategory
        Dictionary<string, string> dictionary = new System.Collections.Generic.Dictionary<string, string>
            {
                { "Acquire Infrastructure", "acqinf" },
                { "Compromise Accounts", "compacc" },
                { "Compromise Infrastructure", "cominf" },
                { "Develop Capabilities", "devcap" },
                { "Establish Accounts", "estacc" },
                { "Obtain Capabilities", "obtcap" },
                { "Stage Capabilities", "stcap" },
                { "Active Scanning", "ascan" },
                { "Gather Victim Host Information", "gathvhi" },
                { "Gather Victim Identity Information", "gathvii" },
                { "Gather Victim Network Information", "gathvni" },
                { "Gather Victim Org Information", "gathvoi" },
                { "Phishing for Information", "phish" },
                { "Search Closed Sources", "scs" },
                { "Search Open Technical Databases", "sotd" },
                { "Search Open Websites/Domains", "sowd" },
                { "Search Victim-Owned Websites", "svow" },
                { "Drive-by Compromise", "dvcomp" },
                { "Exploit Public-Facing Application", "exppfa" },
                { "External Remote Services", "extrs" },
                { "Hardware Additions", "hwadd" },
                { "Supply Chain Compromise", "sccomp" },
                { "Trusted Relationship", "trrel" },
                { "Command and Scripting Interpreter", "c&sint" },
                { "Native API", "natapi" },
                { "Container Administration Command", "cadcom" },
                { "Deploy Container", "depcon" },
                { "Exploitation for Client Execution", "expfce" },
                { "Inter-Process Communication", "intpcom" },
                { "Serverless Execution", "slexec" },
                { "Shared Modules", "shmod" },
                { "System Services", "sysserv" },
                { "User Execution", "usrexe" },
                { "Windows Management Instrumentation", "winmin" },
                { "Account Manipulation", "accman" },
                { "BITS Jobs", "bits" },
                { "Browser Extensions", "browext" },
                { "Compromise Client Software Binary", "ccsb" },
                { "Create Account", "creacc" },
                { "Implant Internal Image", "iintim" },
                { "Office Application Startup", "oappst" },
                { "Pre-OS Boot", "preosb" },
                { "Server Software Component", "sscomp" },
                { "Traffic Signaling", "trsig" },
                { "Valid Accounts", "valacc" },
                { "Scheduled Task/Job", "scht" },
                { "Boot or Logon Autostart Execution", "bolae" },
                { "Abuse Elevation Control Mechanism", "aecm" },
                { "Access Token Manipulation", "acctm" },
                { "Event Triggered Execution", "etexec" },
                { "Boot or Logon Initialization Scripts", "bolis" },
                { "Create or Modify System Process", "comsp" },
                { "Domain Policy Modification", "dpmod" },
                { "Escape to Host", "escth" },
                { "Exploitation for Privilege Escalation", "expfpe" },
                { "Hijack Execution Flow", "hijexf" },
                { "Process Injection", "prinj" },
                { "Build Image on Host", "bimonh" },
                { "Debuger Evasion", "debev" },
                { "Deobfuscate/Decode Files or Information", "dcfoi" },
                { "Direct Volume Access", "dirvac" },
                { "Exploitation for Defense Evasion", "expfde" },
                { "File and Directory Permissions Modification", "fadpmod" },
                { "Hide Artifacts", "hidart" },
                { "Impair Defenses", "impdef" },
                { "Indicator Removal", "indrem" },
                { "Indirect Command Execution", "incexec" },
                { "Masquerading", "masq" },
                { "Modify Authentication Process", "modauthp" },
                { "Modify Cloud Compute Infrastructure", "modcci" },
                { "Modify Registry", "modr" },
                { "Modify System Image", "modsi" },
                { "Network Boundary Bridging", "nwbbr" },
                { "Obfuscated Files or Information", "obfoi" },
                { "Plist File Modification", "plfmod" },
                { "Reflective Code Loading", "refclo" },
                { "Rogue Domain Controller", "rogdc" },
                { "Rootkit", "rootkit" },
                { "Subvert Trust Controls", "strcon" },
                { "System Binary Proxy Execution", "sbpe" },
                { "System Script Proxy Execution", "sspe" },
                { "Template Injection", "tempinj" },
                { "Trusted Developer Utilities Proxy Execution", "tdupe" },
                { "Unused/Unsupported Cloud Regions", "ucreg" },
                { "Use Alternate Authentication Material", "uaam" },
                { "Virtualization/Sandbox Evasion", "vmevas" },
                { "Weaken Encryption", "wencr" },
                { "XSL Script Processing", "xslsp" },
                { "OS Credential Dumping", "crdump" },
                { "Brute Force", "brufor" },
                { "Credentials from Password Stores", "crfps" },
                { "Unsecured Credentials", "unsecc" },
                { "Forced Authentication", "forauth" },
                { "Input Capture", "inpcap" },
                { "Adversary-in-the-Middle", "advitm" },
                { "Exploitation for Credential Access", "expfca" },
                { "Forge Web Credentials", "fwcred" },
                { "Multi-Factor Authentication Interception", "mfaint" },
                { "Multi-Factor Authentication Request Generation", "mfarg" },
                { "Network Sniffing", "nwsniff" },
                { "Steal Application Access Token", "stappat" },
                { "Steal or Forge Authentication Certificates", "saucrt" },
                { "Steal or Forge Kerberos Tickets", "stkerb" },
                { "Steal Web Session Cookie", "stwsc" },
                { "System Information Discovery", "sid" },
                { "Network Service Discovery", "nsd" },
                { "Account Discovery", "ad" },
                { "System Owner/User Discovery", "sodisc" },
                { "Remote System Discovery", "rsdisc" },
                { "System Network Configuration Discovery", "sncdisc" },
                { "System Network Connections Discovery", "sncodisc" },
                { "Permission Groups Discovery", "pgdisc" },
                { "Application Window Discovery", "awdisc" },
                { "Browser Bookmark Discovery", "bbdisc" },
                { "Cloud Infrastructure Discovery", "cidisc" },
                { "Cloud Service Dashboard", "csdash" },
                { "Cloud Service Discovery", "csdisc" },
                { "Cloud Storage Object Discovery", "csodisc" },
                { "Container and Resource Discovery", "cardisc" },
                { "Debugger Evasion", "debeva" },
                { "Domain Trust Discovery", "dtdisc" },
                { "File and Directory Discovery", "faddisc" },
                { "Group Policy Discovery", "gpdisc" },
                { "Password Policy Discovery", "ppdisc" },
                { "Peripheral Device Discovery", "pddisc" },
                { "Process Discovery", "pdisc" },
                { "Query Registry", "qreg" },
                { "Software Discocery", "sdisc" },
                { "System Time Discovery", "stdisc" },
                { "Application Layer Protocol", "applp" },
                { "Non-Application Layer Protocol", "napplp" },
                { "Proxy", "proxy" },
                { "Communication Through Removable Media", "ctrmed" },
                { "Data Encoding", "datenc" },
                { "Data Obfuscation", "datobf" },
                { "Dynamic Resolution", "dynres" },
                { "Encrypted Channel", "encrc" },
                { "Fallback Channels", "fallch" },
                { "Ingress Tool Transfer", "ingttr" },
                { "Multi-Stage Channels", "mschan" },
                { "Protocol Tunneling", "prtunn" },
                { "Remote Access Software", "rasw" },
                { "Web Service", "webserv" },
                { "Automated Exfiltration", "auexf" },
                { "Exfiltration Over C2 Channel", "exfoc2ch" },
                { "Exfiltration Over Alternative Protocol", "exfoap" },
                { "Transfer Data to Cloud Account", "trdtca" },
                { "Exfiltration Over Physical Medium", "exfopm" },
                { "Data Transfer Size Limits", "dtsl" },
                { "Exfiltration Over Other Network Medium", "exfoonm" },
                { "Exfiltration Over Web Service", "exfows" },
                { "Scheduled Transfer", "schtr" },
                { "Endpoint Denial of Service", "edos" },
                { "Defacement", "def" },
                { "Data encrypted", "dencr" },
                { "Inhibit System Recovery", "insr" },
                { "Account Access Removal", "acacre" },
                { "Data Destruction", "datdes" },
                { "Data Manipulation", "datman" },
                { "Disk Wipe", "dwipe" },
                { "Firmware Corruption", "fwcorr" },
                { "Network Denial of Service", "ndos" },
                { "Resource Hijacking", "rhij" },
                { "Service Stop", "serstop" },
                { "System Shutdown/Reboot", "syssh" },
                { "Exploitation of Remote Services", "expors" },
                { "Internal Spearphishing", "intspe" },
                { "Lateral Tool Transfer", "lttr" },
                { "Remote Service Session Hijacking", "rsshij" },
                { "Remote Services", "remser" },
                { "Replication Through Removable Media", "rtrm" },
                { "Software Deployment Tools", "swdt" },
                { "Taint Shared Content", "tscon" },
                { "Email Collection", "emcol" },
                { "Data from Local System", "dfls" },
                { "Automated Collection", "acol" },
                { "Screen Capture", "scrcap" },
                { "Clipboard Data", "cldata" },
                { "Data from Network Shared Drive", "dfnsd" },
                { "Archive Collected Data", "arcd" },
                { "Audio Capture", "audcap" },
                { "Browser Session Hijacking", "brshij" },
                { "Data from Cloud Storage", "dfcs" },
                { "Data from Configuration Repository", "dfcr" },
                { "Data from Information Repositories", "dfir" },
                { "Data from Removable Media", "dfrm" },
                { "Data Staged", "datsta" },
                { "Video Capture", "vidcap" }
            };
        
            //Recognizing the right value
            foreach (KeyValuePair<string, string> pair in dictionary)
            {
                if (pair.Value == subcategory)
                {
                    string subcategoryLong = pair.Key;
                    return subcategoryLong;
                }
            }

            return "Other"; //If nothing is found
    }
}