# -*- coding: utf-8 -*-
"""Ejemplo 07: Ecualizador parametrico con BASS_FX."""

import sys
import time
import ctypes
from basskit.dlls.bass import bass
from basskit.constantes.bass import BASS_UNICODE
from basskit.constantes.bass_fx import BASS_FX_BFX_PEAKEQ
from basskit.estructuras.addons import BASS_BFX_PEAKEQ


def main():
	print("=== Ecualizador Parametrico (BASS_FX) ===\n")

	if len(sys.argv) < 2:
		print("Uso: python 07_ecualizador.py <archivo_audio>")
		return

	bass.BASS_Init(-1, 44100, 0, 0, None)
	ruta = sys.argv[1].encode("utf-16-le") + b"\x00\x00"
	stream = bass.BASS_StreamCreateFile(0, ruta, 0, 0, BASS_UNICODE)
	if stream == 0:
		print(f"Error: {bass.BASS_ErrorGetCode()}")
		bass.BASS_Free()
		return

	# Crear 5 bandas de ecualizador
	bandas = [60, 250, 1000, 4000, 12000]  # Hz
	fx_handles = []

	for freq in bandas:
		fx = bass.BASS_ChannelSetFX(stream, BASS_FX_BFX_PEAKEQ, 0)
		if fx != 0:
			eq = BASS_BFX_PEAKEQ()
			eq.lBand = bandas.index(freq)
			eq.fCenter = float(freq)
			eq.fBandwidth = 2.5
			eq.fGain = 0.0
			eq.lChannel = -1  # Todos los canales
			bass.BASS_FXSetParameters(fx, ctypes.byref(eq))
			fx_handles.append(fx)

	bass.BASS_ChannelPlay(stream, 0)
	print(f"Reproduciendo: {sys.argv[1]}")
	print(f"Bandas: {bandas} Hz\n")

	# Preset: Graves reforzados
	print("[1/3] Preset: Graves reforzados")
	ganancias = [8.0, 4.0, 0.0, -2.0, -4.0]
	for i, (fx, ganancia) in enumerate(zip(fx_handles, ganancias)):
		eq = BASS_BFX_PEAKEQ()
		eq.lBand = i
		eq.fCenter = float(bandas[i])
		eq.fBandwidth = 2.5
		eq.fGain = ganancia
		eq.lChannel = -1
		bass.BASS_FXSetParameters(fx, ctypes.byref(eq))
		print(f"  {bandas[i]:>5} Hz: {ganancia:+.1f} dB")
	time.sleep(4)

	# Preset: Agudos brillantes
	print("\n[2/3] Preset: Agudos brillantes")
	ganancias = [-4.0, -2.0, 0.0, 4.0, 8.0]
	for i, (fx, ganancia) in enumerate(zip(fx_handles, ganancias)):
		eq = BASS_BFX_PEAKEQ()
		eq.lBand = i
		eq.fCenter = float(bandas[i])
		eq.fBandwidth = 2.5
		eq.fGain = ganancia
		eq.lChannel = -1
		bass.BASS_FXSetParameters(fx, ctypes.byref(eq))
		print(f"  {bandas[i]:>5} Hz: {ganancia:+.1f} dB")
	time.sleep(4)

	# Flat
	print("\n[3/3] Preset: Flat")
	for i, fx in enumerate(fx_handles):
		eq = BASS_BFX_PEAKEQ()
		eq.lBand = i
		eq.fCenter = float(bandas[i])
		eq.fBandwidth = 2.5
		eq.fGain = 0.0
		eq.lChannel = -1
		bass.BASS_FXSetParameters(fx, ctypes.byref(eq))
		print(f"  {bandas[i]:>5} Hz:  0.0 dB")
	time.sleep(3)

	bass.BASS_StreamFree(stream)
	bass.BASS_Free()
	print("\nFin del ejemplo.")


if __name__ == "__main__":
	main()
