import { Injectable, inject } from '@angular/core';
import { CantiService } from './canti.service';
import { MyCantiService } from './my-canti.service';
import { ComunitaService } from './comunita.service';

@Injectable({
  providedIn: 'root'
})
export class MediaSessionService {
  private cantiService = inject(CantiService);
  private myCantiService = inject(MyCantiService);
  private comunitaService = inject(ComunitaService);

  public updateMetadata(cantoId: string) {
    if (!('mediaSession' in navigator)) return;

    let canto = this.cantiService.getCantoById(cantoId);
    if (!canto) {
      canto = this.myCantiService.myCanti().find(c => c.id === cantoId);
    }
    if (!canto) {
      canto = this.comunitaService.comunitaCantiPersonali().find(c => c.id === cantoId);
    }
    if (!canto) return;

    const thumb = this.cantiService.getYoutubeThumb(canto.link_youtube) || 'assets/icons/icon-512x512.png';

    if (!('MediaMetadata' in window)) return;

    try {
      (navigator as any).mediaSession.metadata = new (window as any).MediaMetadata({
        title: canto.titolo,
        artist: canto.autore || 'Canti Cristiani',
        album: 'Canti Cristiani',
        artwork: [
          { src: thumb, sizes: '96x96', type: 'image/jpeg' },
          { src: thumb, sizes: '128x128', type: 'image/jpeg' },
          { src: thumb, sizes: '192x192', type: 'image/jpeg' },
          { src: thumb, sizes: '256x256', type: 'image/jpeg' },
          { src: thumb, sizes: '384x384', type: 'image/jpeg' },
          { src: thumb, sizes: '512x512', type: 'image/jpeg' },
        ]
      });
    } catch (e) {
      console.error('Error updating Media Session metadata', e);
    }
  }

  public setPlaybackState(state: 'playing' | 'paused' | 'none') {
    if (!('mediaSession' in navigator)) return;
    (navigator as any).mediaSession.playbackState = state;
  }

  public initActionHandlers(callbacks: {
    play: () => void,
    pause: () => void,
    next?: () => void,
    prev?: () => void,
    seekto?: (time: number) => void
  }) {
    if (!('mediaSession' in navigator)) return;

    const ms = (navigator as any).mediaSession;
    
    ms.setActionHandler('play', callbacks.play);
    ms.setActionHandler('pause', callbacks.pause);
    
    if (callbacks.next) {
      ms.setActionHandler('nexttrack', callbacks.next);
    }
    if (callbacks.prev) {
      ms.setActionHandler('previoustrack', callbacks.prev);
    }
    
    try {
      if (callbacks.seekto) {
        ms.setActionHandler('seekto', (details: any) => {
          if (details.seekTime !== undefined && callbacks.seekto) {
            callbacks.seekto(details.seekTime);
          }
        });
      }
    } catch (e) {}
  }
}
