/**
 *  Copyright © 2026, 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.administer;

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.Form;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import javax.swing.SwingWorker;
import net.javacomm.share.Constants;



/**
 * Eine Raumfilterliste wird gespeichert. Der Worker liefert {@code true}
 * zurück, wenn alle Filter gespeichert wurden.
 */
public class WriteRoomfilterWorker extends SwingWorker<Void, Void> {

  public final static String HTTP = "http";

  private String userid;
  private String password;
  private String filter;

  /**
   * Der Webservice wird initialisiert.
   * 
   * @param userid
   *                 diese userid
   * @param password
   *                 dieses Passwort
   * @param filter
   *                 dieser Raumfilter
   */
  public WriteRoomfilterWorker(String userid, String password, String filter) {
    this.userid = userid;
    this.password = password;
    this.filter = filter;
  }

//  SwingWorker geht immer in den Zustand DONE,
//  egal ob doInBackground() normal endet, eine Exception wirft oder abgebrochen wird.

//  DONE heißt nur: „Der Worker ist fertig“,
//  nicht: „Der Worker war erfolgreich“.
//  



  @Override
  protected Void doInBackground() throws Exception {

    // Exception wird nie in EDT geworfen

    Form form = new Form();
    form.param("userid", userid).param("password", password).param("filter", filter);

    try(Client client = ClientBuilder.newClient()) {
      WebTarget target = client.target(
          Constants.PROTOCOL + Constants.DOMAIN + "/javacommserver/administrator/write/single/roomfilter"
      );
      try(Response response = target.request(MediaType.TEXT_PLAIN).post(Entity.form(form))) {
        if (response.getStatusInfo() == Response.Status.BAD_REQUEST) {
          firePropertyChange(
              HTTP, response.getStatusInfo(),
              "Invalid request parameter: 'filter' is empty. A non-empty filter name is required."
          );
        }
        else if (response.getStatusInfo() == Response.Status.OK) {
          firePropertyChange(HTTP, response.getStatusInfo(), filter);
        }
      }
    }
    return null;

  }

}
