/**
 *  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.protocol.CBlock;
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 pseudoid;
  private CBlock cblock;
  private String filter;

  /**
   * Der Webservice wird initialisiert.
   * 
   * @param pseudoid
   *                 diese userid
   * @param password
   *                 dieses Passwort
   * @param filter
   *                 dieser Raumfilter
   */
  public WriteRoomfilterWorker(String pseudoid, CBlock cblock, String filter) {
    this.pseudoid = pseudoid;
    this.cblock = cblock;
    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("pseudoid", pseudoid).param("cblock", cblock.toString()).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;

  }

}
