/**
 *  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.base;

import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.swing.SwingWorker;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.ClientProperties;
import net.javacomm.share.Constants;



/**
 * Screenshot wird vom Server geladen.
 */
public class LoadScreenshotWorker extends SwingWorker<BufferedImage, Void> {

  private String userid;

  static {
    ImageIO.setUseCache(false);
  }

  /**
   * Webservice initialisieren
   * 
   * @param userid
   *               das Bild stammt von diesem Benutzer
   */
  public LoadScreenshotWorker(String userid) {
    this.userid = userid;
  }



  @Override
  protected BufferedImage doInBackground() throws Exception {
    return loadScreenshot(userid);
  }



  /**
   * 
   * @param domain
   *               con dieser Domäne werden die Bilder geladen
   * @param userid
   *               von diesem Anwender stammen die Bilder
   * @throws IOException
   */
  private BufferedImage loadScreenshot(String userid) throws IOException {
    BufferedImage image = null;
    ClientConfig config = new ClientConfig();
    config.property(ClientProperties.CONNECT_TIMEOUT, 200);
    config.property(ClientProperties.READ_TIMEOUT, 500);
    try(Client client = ClientBuilder.newClient(config)) {
      StringBuilder url = new StringBuilder();
      url.append(Constants.PROTOCOL).append(Constants.DOMAIN).append("/javacommserver/screenshot/load/");
      WebTarget webtarget = client.target(url.toString());
      try(
        Response response = webtarget.request(MediaType.APPLICATION_OCTET_STREAM).header("userid", userid)
            .get();
        InputStream is = response.readEntity(InputStream.class)
      ) {
        image = ImageIO.read(is);
      }
    }
    return image;
  }
}
