﻿using System;
using System.Reflection;
using HarmonyLib;

namespace undead_universal_patch.Patches
{
    [HarmonyPatch]
    class WWWPatch
    {
        const string TargetTypeName = "UnityEngine.WWW";
        const string TargetMethodName = "InitWWW";
        const string Description = "Legacy WWW patch";
        static readonly Type targetType = AccessTools.TypeByName(TargetTypeName);

        static bool Prepare()
        {
            if (GenericConfig.IsNameserver.Value) return false;
            if (targetType == null) 
            {
                Plugin.Log.LogWarning($"'{Description}' disabled. The type for this patch was not found.");
                return false;
            }
            if (TargetMethodName != null)
            {
                MethodInfo targetMethod = AccessTools.Method(targetType, TargetMethodName);
                if (targetMethod == null)
                {
                    Plugin.Log.LogWarning($"'{Description}' disabled. ({TargetTypeName}.{TargetMethodName} not found)");
                    return false;
                }
            }

            Plugin.Log.LogInfo($"'{Description}' succeeded validation.");
            return true;
        }

        static MethodBase TargetMethod()
        {
            return AccessTools.Method(targetType, TargetMethodName, [ typeof(string), typeof(byte[]), typeof(string[]) ]);
        }

        [HarmonyPrefix]
        static bool Prefix(ref string url)
        {
            if (url == "http://www.againstgrav.com/motd")
            {
                url = $"{ConfigUtils.GetGameserverBaseUrl()}/api/legacyMoTD/v1";
                Plugin.Log.LogInfo("Redirected legacy MoTD.");
            }
            if (GenericConfig.DisableGoogleAnalytics.Value && url == "http://www.google-analytics.com/collect") return false;
            url = PatchUtils.RewriteUrlForGameserver(url).ToString();

            if (GenericConfig.LogAllRequests.Value) Plugin.Log.LogDebug($"Request URL: {url}");
            return true;
		}
    }
}
