using CUE4Parse.Compression;
using CUE4Parse.Encryption.Aes;
using CUE4Parse.FileProvider;
using CUE4Parse.MappingsProvider;
using CUE4Parse.UE4.Assets.Exports.Actor;
using CUE4Parse.UE4.Assets.Exports.Engine;
using CUE4Parse.UE4.Assets.Exports.Texture;
using CUE4Parse.UE4.Assets.Objects.Properties;
using CUE4Parse.UE4.Objects.Core.Misc;
using CUE4Parse.UE4.Objects.UObject;
using CUE4Parse.UE4.Versions;
using Newtonsoft.Json;

class DumpByDaylight
{
    private const string _pakDir = "D:\\XboxGames\\Dead By Daylight\\Content\\DeadByDaylight\\Content\\Paks";
    private const string _aesKey = "0x22B1639B548124925CF7B9CBAA09F9AC295FCF0324586D6B37EE1D42670B39B3";
    private const string _mappingURL = "https://git.neru.rip/neru/UnlockedByDaylight/raw/branch/main/res/mappings/latest-xbox.usmap";

    public static async Task<string?> DownloadMappingFileAsync(string url, string savePath)
    {
        try
        {
            using (var httpClient = new HttpClient())
            {
                Console.WriteLine("downloading mapping file...");
                var bytes = await httpClient.GetByteArrayAsync(url);
                await File.WriteAllBytesAsync(savePath, bytes);
                Console.WriteLine($"mapping file downloaded to: {savePath}");
                return savePath;
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"failed to download mapping: {ex.Message}");
            return null;
        }
    }

    static async Task Main(string[] args)
    {
        // mapping
        string mappingPath = Path.Combine(Path.GetTempPath(), "DeadByDaylight.usmap");
        string? downloadedMapping = await DownloadMappingFileAsync(_mappingURL, mappingPath);

        if (string.IsNullOrEmpty(downloadedMapping))
        {
            Console.WriteLine("failed to download mapping file, press any key to exit");
            Console.ReadKey();
            return;
        }

        ZlibHelper.Initialize();

        var oodlePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, OodleHelper.OodleFileName);
        OodleHelper.Initialize(oodlePath);


        // parsing setup
        var version = new VersionContainer(EGame.GAME_DeadByDaylight, ETexturePlatform.DesktopMobile);
        var provider = new DefaultFileProvider(_pakDir, SearchOption.TopDirectoryOnly, version);
        provider.MappingsContainer = new FileUsmapTypeMappingsProvider(downloadedMapping);

        provider.Initialize();
        provider.SubmitKey(new FGuid(), new FAesKey(_aesKey));
        provider.Mount();

        Console.WriteLine("\nProvider Initialized. Extracting Databases...");

        var dataPak = provider.GetArchive("pakchunk4-WinGDK.utoc");

        /*
         *  itemdb dump
         */
        var searchPaths = dataPak.Files.Keys.Where(x => x.Contains($"/ItemDB.uasset", StringComparison.OrdinalIgnoreCase)).ToList();
        var camperItems = new List<string>();

        var slasherPowers = new List<string>();

        foreach (var path in searchPaths)
        {
            var cleanPath = path.Contains('.') ? path.Substring(0, path.LastIndexOf('.')) : path;
            if (provider.TryLoadPackageObject<UDataTable>(cleanPath, out var dataTable))
            {
                Console.WriteLine($"getting items / powers from {Path.GetFullPath(path)}");

                foreach (var row in dataTable.RowMap)
                {
                    var roleProperty = row.Value.Properties.FirstOrDefault(p => p.Name.Text == "Role");
                    var typeProperty = row.Value.Properties.FirstOrDefault(p => p.Name.Text == "Type");
                    if (typeProperty?.Tag is EnumProperty typeProp && roleProperty?.Tag is EnumProperty roleProp)
                    {
                        string typeName = typeProp.Value.ToString() ?? "null";
                        string roleName = roleProp.Value.ToString() ?? "null";

                        if (roleName == "EPlayerRole::VE_Slasher")
                            slasherPowers.Add(row.Key.Text);
                        else
                            camperItems.Add(row.Key.Text);
                    }
                }
            }
        }

        var itemsSerialized = new
        {
            Campers = camperItems.OrderBy(x => x).ToList(),
            Slashers = slasherPowers.OrderBy(x => x).ToList()
        };
        File.WriteAllText("items.json", JsonConvert.SerializeObject(itemsSerialized, Formatting.Indented));

        /*
         *  addon dump
         */
        searchPaths = dataPak.Files.Keys.Where(x => x.Contains($"/ItemAddonDB.uasset", StringComparison.OrdinalIgnoreCase)).ToList();
        var camperAddons = new List<string>();
        var slasherAddons = new List<string>();

        foreach (var path in searchPaths)
        {
            var cleanPath = path.Contains('.') ? path.Substring(0, path.LastIndexOf('.')) : path;
            if (provider.TryLoadPackageObject<UDataTable>(cleanPath, out var dataTable))
            {
                Console.WriteLine($"getting item / power addons from {Path.GetFullPath(path)}");

                foreach (var row in dataTable.RowMap)
                {
                    bool isSlasherAddon = false;
                    var roleProperty = row.Value.Properties.FirstOrDefault(p => p.Name.Text == "Role");
                    if (roleProperty?.Tag is EnumProperty roleEnumProp)
                    {
                        string roleName = roleEnumProp.Value.ToString() ?? "null";
                        if (roleName == "EPlayerRole::VE_Slasher")
                            isSlasherAddon = true;
                    }

                    if (isSlasherAddon)
                        slasherAddons.Add(row.Key.Text);
                    else
                        camperAddons.Add(row.Key.Text);
                }
            }
        }

        var addonsSerialized = new
        {
            Slashers = slasherAddons.OrderBy(x => x).ToList(),
            Campers = camperAddons.OrderBy(x => x).ToList()
        };
        File.WriteAllText("addons.json", JsonConvert.SerializeObject(addonsSerialized, Formatting.Indented));

        /*
         *  offerings
         */
        searchPaths = dataPak.Files.Keys.Where(x => x.Contains($"/OfferingDB.uasset", StringComparison.OrdinalIgnoreCase)).ToList();

        var camperOfferings = new List<string>();
        var slasherOfferings = new List<string>();

        foreach (var path in searchPaths)
        {
            var cleanPath = path.Contains('.') ? path.Substring(0, path.LastIndexOf('.')) : path;
            if (provider.TryLoadPackageObject<UDataTable>(cleanPath, out var dataTable))
            {
                Console.WriteLine($"getting offerings from {Path.GetFullPath(path)}");

                foreach (var row in dataTable.RowMap)
                {
                    var roleProperty = row.Value.Properties.FirstOrDefault(p => p.Name.Text == "Role");
                    if (roleProperty?.Tag is EnumProperty roleEnumProp)
                    {
                        string roleName = roleEnumProp.Value.ToString() ?? "null";
                        if (roleName == "EPlayerRole::VE_Slasher")
                            slasherOfferings.Add(row.Key.Text);
                        else
                            camperOfferings.Add(row.Key.Text);
                    }
                }
            }
        }
        var offeringsSerialized = new
        {
            Slashers = slasherOfferings.OrderBy(x => x).ToList(),
            Campers = camperOfferings.OrderBy(x => x).ToList()
        };
        File.WriteAllText("offerings.json", JsonConvert.SerializeObject(offeringsSerialized, Formatting.Indented));

        /*
         * perks
         */
        searchPaths = dataPak.Files.Keys.Where(x => x.Contains($"/PerkDB.uasset", StringComparison.OrdinalIgnoreCase)).ToList();

        var slasherPerks = new List<string>();
        var camperPerks = new List<string>();

        foreach (var path in searchPaths)
        {
            var cleanPath = path.Contains('.') ? path.Substring(0, path.LastIndexOf('.')) : path;
            if (provider.TryLoadPackageObject<UDataTable>(cleanPath, out var dataTable))
            {
                Console.WriteLine($"getting perks from {Path.GetFullPath(path)}");

                foreach (var row in dataTable.RowMap)
                {
                    var roleProperty = row.Value.Properties.FirstOrDefault(p => p.Name.Text == "Role");
                    if (roleProperty?.Tag is EnumProperty roleEnumProp)
                    {
                        string roleName = roleEnumProp.Value.ToString() ?? "null";
                        if (roleName == "EPlayerRole::VE_Slasher")
                            slasherPerks.Add(row.Key.Text);
                        else
                            camperPerks.Add(row.Key.Text);
                    }
                }
            }
        }

        var perksSerialized = new
        {
            Slashers = slasherPerks.OrderBy(x => x).ToList(),
            Campers = camperPerks.OrderBy(x => x).ToList()
        };
        File.WriteAllText("perks.json", JsonConvert.SerializeObject(perksSerialized, Formatting.Indented));

        Console.WriteLine("\nAll dumper operations finished. Press any key to Close.");
        Console.ReadKey();
    }
}
