/**
 *  Copyright © 2025, Luis Andrés Lange <https://javacomm.net>
 *
 *  This Source Code Form is subject to the terms of the Mozilla Public
 *  License, v. 2.0. If a copy of the MPL was not distributed with this
 *  file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 *  ----------------------------------------------------------------------------
 *
 *  Exhibit B - "Incompatible With Secondary Licenses" Notice
 *
 *  This Source Code Form is "Incompatible With Secondary Licenses",
 *  as defined by the Mozilla Public License, v. 2.0.
 *
 */
package net.javacomm.client.streams;

import javax.swing.SwingWorker;
import uk.co.caprica.vlcj.media.MediaEventListener;
import uk.co.caprica.vlcj.player.base.ControlsApi;
import uk.co.caprica.vlcj.player.base.EventApi;
import uk.co.caprica.vlcj.player.base.MediaPlayerEventListener;
import uk.co.caprica.vlcj.player.embedded.EmbeddedMediaPlayer;



/**
 * This SwingWorker terminates a MediaStream.
 * 
 */
public class IptvSwingWorker extends SwingWorker<Void, Void> {

  private EmbeddedMediaPlayer embedded;
  private MediaEventListener mediaEventListener;
  private MediaPlayerEventListener mediaPlayerListener;

  public IptvSwingWorker(EmbeddedMediaPlayer embedded, MediaEventListener mediaEventListener, MediaPlayerEventListener mediaPlayerListener) {
    this.embedded = embedded;
    this.mediaEventListener = mediaEventListener;
    this.mediaPlayerListener = mediaPlayerListener;
  }



  @Override
  protected Void doInBackground() throws EmbeddedPlayerException {
    stopStream();
    return null;
  }



  /**
   * Der aktuelle Stream wird abgebrochen.
   * 
   * @throws EmbeddedPlayerException
   *                                 der Stream konnte nicht geschlossen werden
   */
  void stopStream() throws EmbeddedPlayerException {
    try {
      EventApi eventsAPI = embedded.events();

      if (eventsAPI != null) {
        eventsAPI.removeMediaEventListener(mediaEventListener);
        eventsAPI.removeMediaPlayerEventListener(mediaPlayerListener);
      }

      if (embedded != null) {
        ControlsApi controlsApi = embedded.controls();
        controlsApi.stop();
        embedded.release();
        embedded = null;
      }
    }
    catch (Throwable cause) {
      throw new EmbeddedPlayerException(cause);
    }
  }

}
