using System.Runtime.CompilerServices;
using RWCustom;
using UnityEngine;
using static AbstractPhysicalObject;

namespace JilloSlug;

// fisobs? never heard of them

public static class JilloSlimeMold {
    private static ConditionalWeakTable<AbstractPhysicalObject, StrongBox<bool>> JilloMolds = new ConditionalWeakTable<AbstractPhysicalObject, StrongBox<bool>>();

    public static bool IsJilloSlimeMold(AbstractPhysicalObject mold) {
        return JilloMolds.TryGetValue(mold, out var isJillo) && isJillo.Value;
    }
    public static bool IsJilloSlimeMold(SlimeMold mold) {
        return IsJilloSlimeMold(mold.abstractPhysicalObject);
    }

    public static void SetJilloSlimeMold(AbstractPhysicalObject mold, bool value = true) {
        JilloMolds.Add(mold, new StrongBox<bool>(value));
    }
    public static void SetJilloSlimeMold(SlimeMold mold, bool value = true) {
        SetJilloSlimeMold(mold.abstractPhysicalObject, value);
    }

    public static void AddHooks() {
        On.SlimeMold.ApplyPalette += SlimeMold_ApplyPalette;
    }

    private static void SlimeMold_ApplyPalette(On.SlimeMold.orig_ApplyPalette orig, SlimeMold self, RoomCamera.SpriteLeaser sLeaser, RoomCamera rCam, RoomPalette palette) {
        if (!IsJilloSlimeMold(self)) {
            orig(self, sLeaser, rCam, palette);
            return;
        }
        self.darkMode = Mathf.InverseLerp(0.3f, 0.9f, palette.darkness);
        self.color = SlimeMoldColorFromPalette(palette);
    }

    private static Color SlimeMoldColorFromPalette(RoomPalette palette) {
        Color col = Color.Lerp(
            Custom.HSL2RGB(Mathf.Lerp(0.05f, 0.045f, palette.darkness), 0.59f, 0.63f),
            palette.fogColor,
            Mathf.Lerp(0.15f, 0.25f, palette.fogAmount) * Mathf.Lerp(0.1f, 0.5f, palette.darkness)
        );
        col.a = 0.7f;
        return col;
    }
}
