/**
 *  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.Entity;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.GenericType;
import jakarta.ws.rs.core.MediaType;
import java.util.ArrayList;
import javax.swing.SwingWorker;
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import net.javacomm.restserver.MessageBodyTransferBenutzerkonto;
import net.javacomm.share.Constants;
import net.javacomm.transfer.TransferBenutzerkonto;



/**
 * Dieser Webservice (Jersey) liest alle Benutzerkonten aus.
 * 
 */
public class ReadBenutzerkontenWorker extends SwingWorker<ArrayList<TransferBenutzerkonto>, Void> {

  private String domain;
  private String admin;
  private String password;

  /**
   * Webservice initialisieren.
   * 
   * 
   * @param domain
   *                 an diese Domäne wird gesendet
   * @param admin
   *                 dieser Administrator
   * @param password
   *                 dieses Passwort
   */
  public ReadBenutzerkontenWorker(String domain, String admin, String password) {
    this.domain = domain;
    this.admin = admin;
    this.password = password;
  }



  @Override
  protected ArrayList<TransferBenutzerkonto> doInBackground() throws Exception {
    ArrayList<TransferBenutzerkonto> result = null;
    try(Client client = ClientBuilder.newClient();) {
      client.register(MessageBodyTransferBenutzerkonto.class);
      client.register(MultiPartFeature.class);
      StringBuilder url = new StringBuilder(Constants.PROTOCOL).append(domain)
          .append("/javacommserver/administrator/read/accounts");
      WebTarget webtarget = client.target(url.toString());
      try(FormDataMultiPart multipart = new FormDataMultiPart()) {
        multipart.field("admin", admin);
        multipart.field("password", password);
        GenericType<ArrayList<TransferBenutzerkonto>> configType = new GenericType<>() {};
        result = webtarget.request(MediaType.APPLICATION_JSON)
            .post(Entity.entity(multipart, multipart.getMediaType()), configType);
        return result;
      }
    }
  }

}
