from django.shortcuts import render, get_object_or_404, redirect
from .models import Artist, Preset, EffectModule, AudioEngineSettings

def index(request):
    featured_presets = Preset.objects.filter(is_featured=True)[:6]
    artists = Artist.objects.all()
    return render(request, 'core/index.html', {
        'featured_presets': featured_presets,
        'artists': artists
    })

def artist_detail(request, slug):
    artist = get_object_or_404(Artist, slug=slug)
    presets = artist.presets.all()
    return render(request, 'core/artist_detail.html', {
        'artist': artist,
        'presets': presets
    })

def preset_detail(request, slug):
    preset = get_object_or_404(Preset, slug=slug)
    steps = preset.steps.all().select_related('module')
    return render(request, 'core/preset_detail.html', {
        'preset': preset,
        'steps': steps
    })

def audio_settings(request):
    settings, created = AudioEngineSettings.objects.get_or_create(pk=1)
    if request.method == 'POST':
        settings.driver_type = request.POST.get('driver_type')
        settings.buffer_size = int(request.POST.get('buffer_size', 128))
        settings.sample_rate = int(request.POST.get('sample_rate', 44100))
        settings.save()
        return redirect('audio_settings')
    
    return render(request, 'core/settings.html', {
        'settings': settings
    })

def standalone_download(request):
    return render(request, 'core/standalone.html')