import { Button } from "antd";
import { subscribe } from "valtio";

import { settingStore } from "@/stores/settingStore";

import { audioContextManger } from "../core/manager";
import { AudioActionType } from "../type";

export function playEffect(effect: AudioActionType) {
  if (!settingStore.audio.enableSoundEffects) return;
  return audioContextManger.playEffect(
    effect,
    settingStore.audio.soundEffectsVolume,
  );
}

subscribe(settingStore.audio, () => {
  audioContextManger.updateEffectVolume(settingStore.audio.soundEffectsVolume);
});

Reflect.set(
  Button,
  "render",
  new Proxy(Reflect.get(Button, "render"), {
    apply(target, thisArg, args) {
      const [props] = args;
      const { onClick } = props;
      // onClick is read-only, so we need to use the following code
      const _onClick: React.MouseEventHandler<HTMLElement> = (...args) => {
        playEffect(AudioActionType.SOUND_BUTTON);
        onClick(...args);
      };
      return target.apply(thisArg, [
        {
          ...props,
          onClick: _onClick,
        },
        ...args.slice(1),
      ]);
    },
  }),
);
