# -*- coding: utf-8 -*-
"""Ejemplo 06: Efectos de tempo y pitch con BASS_FX."""

import sys
import time
import ctypes
from basskit.dlls.bass import bass
from basskit.dlls.bass_fx import bass_fx
from basskit.constantes.bass import BASS_STREAM_DECODE, BASS_UNICODE, BASS_ATTRIB_VOL
from basskit.constantes.bass_fx import (
	BASS_FX_FREESOURCE, BASS_ATTRIB_TEMPO,
	BASS_ATTRIB_TEMPO_PITCH, BASS_ATTRIB_TEMPO_FREQ,
)


def main():
	print("=== Efectos Tempo y Pitch (BASS_FX) ===\n")

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

	bass.BASS_Init(-1, 44100, 0, 0, None)
	ruta = sys.argv[1].encode("utf-16-le") + b"\x00\x00"

	# Crear stream de decodificacion
	stream_decode = bass.BASS_StreamCreateFile(
		0, ruta, 0, 0, BASS_STREAM_DECODE | BASS_UNICODE
	)
	if stream_decode == 0:
		print(f"Error al abrir archivo: {bass.BASS_ErrorGetCode()}")
		bass.BASS_Free()
		return

	# Crear stream con soporte de tempo
	stream = bass_fx.BASS_FX_TempoCreate(stream_decode, BASS_FX_FREESOURCE)
	if stream == 0:
		print(f"Error al crear stream tempo: {bass.BASS_ErrorGetCode()}")
		bass.BASS_Free()
		return

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

	# Velocidad normal
	print("[1/4] Velocidad normal (3 seg)")
	time.sleep(3)

	# Mas rapido (+30%)
	bass.BASS_ChannelSetAttribute(stream, BASS_ATTRIB_TEMPO, 30.0)
	print("[2/4] Tempo +30% (mas rapido, mismo pitch) - 3 seg")
	time.sleep(3)

	# Normal pero pitch +3 semitonos
	bass.BASS_ChannelSetAttribute(stream, BASS_ATTRIB_TEMPO, 0.0)
	bass.BASS_ChannelSetAttribute(stream, BASS_ATTRIB_TEMPO_PITCH, 3.0)
	print("[3/4] Pitch +3 semitonos (mismo tempo) - 3 seg")
	time.sleep(3)

	# Mas lento (-20%) con pitch -2
	bass.BASS_ChannelSetAttribute(stream, BASS_ATTRIB_TEMPO, -20.0)
	bass.BASS_ChannelSetAttribute(stream, BASS_ATTRIB_TEMPO_PITCH, -2.0)
	print("[4/4] Tempo -20%, pitch -2 semitonos - 3 seg")
	time.sleep(3)

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


if __name__ == "__main__":
	main()
