using System;
using System.Runtime.InteropServices;

public class RegionSound : IDisposable
{
    /// Pixels below this are silent AND not drawn in the overlay, so what you
    /// see is where you can hear it. Adjustable live in the tuner (Ctrl+T).
    public static int MinIntensity = 12;

    public int    Index;              // 0,1 = heart; 2..6 = breath
    public string Name;
    public string SoundPath;          // for the legend / waveform
    public Gdk.Pixbuf Map;            // raw, NOT black-keyed — audio reference
    public AudioEngine.Voice Voice;   // owned by AudioEngine's cache
    public WaveData Wave;             // waveform of this region's sound (may be null)
    public float  Volume;
    public bool   Enabled = true;

    private byte[] _px;
    private int _w, _h, _stride, _ch;

    public bool IsHeart { get { return Index <= 1; } }

    public void CachePixels()
    {
        if (Map == null) return;
        _w = Map.Width; _h = Map.Height;
        _stride = Map.Rowstride; _ch = Map.NChannels;

        int len = _stride * (_h - 1) + _w * _ch;    // last row is short — don't overrun
        _px = new byte[len];
        Marshal.Copy(Map.Pixels, _px, 0, len);
    }

    /// u,v are 0..1 across the map, from MapWindow.BodyToMapUV.
    public int IntensityAt(double u, double v)
    {
        if (_px == null) return 0;
        int x = (int)(u * _w), y = (int)(v * _h);
        if (x < 0 || y < 0 || x >= _w || y >= _h) return 0;

        int i = y * _stride + x * _ch;
        if (i + 2 >= _px.Length) return 0;

        byte r = _px[i], b = _px[i + 2];
        return r != 0 ? r : b;                      // Python: R if R != 0 else B
    }

    /// Python's (v/255)^(1/9.5) is only the first step of Form2's curve; the
    /// result is then converted through decibels (AudioEngine.VolumeCurve).
    /// Using the first step directly as the gain made a pixel value of 1 play
    /// at 56% — the faint edge of every map was almost full volume.
    public float VolumeAt(double u, double v)
    {
        if (!Enabled) return 0f;
        int val = IntensityAt(u, v);
        if (val < MinIntensity) return 0f;

        float vol = AudioEngine.VolumeCurve(val);
        if (!IsHeart) vol *= 0.5f;                  // Python: breath halved
        return Math.Max(0f, Math.Min(1f, vol));
    }

    public void Dispose()
    {
        if (Map != null) { Map.Dispose(); Map = null; }
        _px = null;
        Voice = null;                               // engine keeps and reuses it
        Wave = null;
    }
}