/*
   * (non-Javadoc)
   *
   * @see org.deegree.enterprise.control.AbstractListener#actionPerformed(org.deegree.enterprise.control.FormEvent)
   */
  @Override
  public void actionPerformed(FormEvent event) {

    RPCWebEvent rpc = (RPCWebEvent) event;
    RPCMethodCall mc = rpc.getRPCMethodCall();

    // notice that a RPC parameter is not named but we know our method call
    // contains just one parameter
    RPCParameter param = mc.getParameters()[0];

    // we also know that the parameters value is an RPC structure (mapped to RPCStruct class)
    RPCStruct struct = (RPCStruct) param.getValue();

    // at least we know the names of the structure members and their data type
    Double minx = (Double) struct.getMember("minx").getValue();
    Double miny = (Double) struct.getMember("miny").getValue();
    Double maxx = (Double) struct.getMember("maxx").getValue();
    Double maxy = (Double) struct.getMember("maxy").getValue();

    double[] box =
        adjustBoundingBox(
            minx.doubleValue(), miny.doubleValue(), maxx.doubleValue(), maxy.doubleValue());

    ServletRequest req = this.getRequest();
    req.setAttribute("BBOX", box);
  }
  @Override
  public void actionPerformed(FormEvent event) {

    // the Role for which the rights are to be set
    int roleId = -1;
    // array of ints, ids of Layers (SecuredObjects) for which
    // the Role has access rights
    int[] layers = null;
    // corresponding maps of key (PropertyName) / value-pairs that
    // constitute access constraints
    Map<String, Object>[] layerConstraints = null;

    SecurityAccessManager manager = null;
    SecurityTransaction transaction = null;

    try {
      RPCWebEvent ev = (RPCWebEvent) event;
      RPCMethodCall rpcCall = ev.getRPCMethodCall();
      RPCParameter[] params = rpcCall.getParameters();

      // validates the incomming method call and extracts the roleID
      roleId = validate(params);

      RPCParameter[] layerParams = (RPCParameter[]) params[1].getValue();
      layers = new int[layerParams.length];
      layerConstraints = new Map[layerParams.length];
      extractLayerValues(layers, layerConstraints, layerParams);

      // extract FeatureType rights
      if (!(params[2].getValue() instanceof RPCParameter[])) {
        throw new RPCException(Messages.getMessage("IGEO_STD_STORERIGHTS_THIRD_PARAM"));
      }

      // array of ints, ids of FeatureTypes (SecuredObjects) for which
      // the Role has access rights
      FeatureTypeRight[] featureTypes = extractFeatureTypeValues(params);

      transaction = SecurityHelper.acquireTransaction(this);
      SecurityHelper.checkForAdminRole(transaction);

      manager = SecurityAccessManager.getInstance();
      User user = transaction.getUser();
      Role role = transaction.getRoleById(roleId);

      // perform access check
      if (!user.hasRight(transaction, "update", role)) {
        getRequest().setAttribute("SOURCE", this.getClass().getName());
        String s = Messages.getMessage("IGEO_STD_STORERIGHTS_MISSING_RIGHTS", role.getName());
        getRequest().setAttribute("MESSAGE", s);
        setNextPage("error.jsp");
        return;
      }

      // set/delete access rights for Layers
      SecuredObject[] presentLayers = transaction.getAllSecuredObjects(ClientHelper.TYPE_LAYER);
      setAccessRightsForLayers(layers, layerConstraints, transaction, role, presentLayers);

      // set/delete access rights for FeatureTypes
      SecuredObject[] presentFeatureTypes =
          transaction.getAllSecuredObjects(ClientHelper.TYPE_FEATURETYPE);
      setAccessRightsForFeatureTypes(featureTypes, transaction, role, presentFeatureTypes);

      manager.commitTransaction(transaction);
      transaction = null;
      String s = Messages.getMessage("IGEO_STD_STORERIGHTS_SUCCESS", role.getID());
      getRequest().setAttribute("MESSAGE", s);
    } catch (RPCException e) {
      getRequest().setAttribute("SOURCE", this.getClass().getName());
      String s = Messages.getMessage("IGEO_STD_STORERIGHTS_INVALID_REQ", e.getMessage());
      getRequest().setAttribute("MESSAGE", s);
      setNextPage("error.jsp");
      LOG.logDebug(e.getMessage(), e);
    } catch (GeneralSecurityException e) {
      getRequest().setAttribute("SOURCE", this.getClass().getName());
      String s = Messages.getMessage("IGEO_STD_STORERIGHTS_ERROR", e.getMessage());
      getRequest().setAttribute("MESSAGE", s);
      setNextPage("error.jsp");
      LOG.logDebug(e.getMessage(), e);
    } finally {
      if (manager != null && transaction != null) {
        try {
          manager.abortTransaction(transaction);
        } catch (GeneralSecurityException e) {
          LOG.logDebug(e.getMessage(), e);
        }
      }
    }
  }
  /**
   * appends the selected layers of a WMS to the passed <code>ViewContext</code>
   *
   * @param context
   * @throws ContextException
   * @throws MalformedURLException
   * @throws PortalException
   * @throws InvalidCapabilitiesException
   */
  private void appendWMS(RPCWebEvent rpc, ViewContext context)
      throws MalformedURLException, ContextException, PortalException,
          InvalidCapabilitiesException {

    RPCStruct struct = (RPCStruct) rpc.getRPCMethodCall().getParameters()[0].getValue();
    URL url = new URL((String) struct.getMember("WMSURL").getValue());
    String name = (String) struct.getMember("WMSNAME").getValue();
    String version = (String) struct.getMember("WMSVERSION").getValue();
    String layers = (String) struct.getMember("LAYERS").getValue();
    String formatName = (String) struct.getMember("FORMAT").getValue();
    boolean useAuthentification = false;
    if (struct.getMember("useAuthentification") != null) {
      String tmp = (String) struct.getMember("useAuthentification").getValue();
      useAuthentification = "true".equalsIgnoreCase(tmp);
    }

    List<String> list = StringTools.toList(layers, ";", true);

    WMSCapabilitiesDocument capa = null;
    try {
      StringBuffer sb = new StringBuffer(500);
      if ("1.0.0".equals(version)) {
        sb.append(url.toExternalForm()).append("?request=capabilities&service=WMS");
      } else {
        sb.append(url.toExternalForm()).append("?request=GetCapabilities&service=WMS");
      }
      if (useAuthentification) {
        HttpSession session = ((HttpServletRequest) getRequest()).getSession();
        String user =
            ((org.apache.jetspeed.om.security.BaseJetspeedUser)
                    session.getAttribute("turbine.user"))
                .getUserName();
        String password =
            ((org.apache.jetspeed.om.security.BaseJetspeedUser)
                    session.getAttribute("turbine.user"))
                .getPassword();
        if (!"anon".equals(user)) {
          sb.append("&user="******"&password="******"GetCapabilites for added WMS", sb.toString());
      capa = WMSCapabilitiesDocumentFactory.getWMSCapabilitiesDocument(new URL(sb.toString()));
    } catch (Exception e) {
      LOG.logError(e.getMessage(), e);
      String msg = null;
      if ("1.0.0".equals(version)) {
        msg =
            StringTools.concat(
                500,
                "could not load WMS capabilities from: ",
                new URL(url.toExternalForm() + "?request=capabilities&service=WMS"),
                "; reason: ",
                e.getMessage());
      } else {
        msg =
            StringTools.concat(
                500,
                "could not load WMS capabilities from: ",
                new URL(url.toExternalForm() + "?request=GetCapabilities&service=WMS"),
                "; reason: ",
                e.getMessage());
      }
      throw new PortalException(msg);
    }
    WMSCapabilities capabilities = (WMSCapabilities) capa.parseCapabilities();
    String rootTitle = capabilities.getLayer().getTitle();

    // ----------------------------------------------------------------------------
    // stuff required by layerlist tree view
    Node root = context.getGeneral().getExtension().getLayerTreeRoot();
    // check if Node width this title already exists
    Node[] nodes = root.getNodes();
    int newNodeId = -1;
    for (int j = 0; j < nodes.length; j++) {
      if (nodes[j].getTitle().equals(rootTitle)) {
        newNodeId = nodes[j].getId();
        break;
      }
    }
    if (newNodeId == -1) {
      newNodeId = root.getMaxNodeId() + 1;
      Node newNode = new Node(newNodeId, root, rootTitle, true, false);
      Node[] newNodes = new Node[nodes.length + 1];
      newNodes[0] = newNode;
      for (int j = 0; j < nodes.length; j++) {
        newNodes[j + 1] = nodes[j];
      }

      root.setNodes(newNodes);
    }
    // ----------------------------------------------------------------------------
    for (int i = 0; i < list.size(); i++) {
      String[] lay = StringTools.toArray(list.get(i), "|", false);
      Server server = new Server(name, version, "OGC:WMS", url, capabilities);
      String srs = context.getGeneral().getBoundingBox()[0].getCoordinateSystem().getPrefixedName();
      Format format = new Format(formatName, true);
      FormatList fl = new FormatList(new Format[] {format});
      // read available styles from WMS capabilities and add them
      // to the WMC layer
      org.deegree.ogcwebservices.wms.capabilities.Layer wmslay = capabilities.getLayer(lay[0]);
      org.deegree.ogcwebservices.wms.capabilities.Style[] wmsstyles = wmslay.getStyles();
      Style[] styles = null;
      if (wmsstyles == null || wmsstyles.length == 0) {
        // a wms capabilities layer may offeres one or more styles for
        // a layer but it don't have to. But WMC must have at least one
        // style for each layer; So we set a default style in the case
        // a wms does not declares one
        styles = new Style[1];
        styles[0] = new Style("", "default", "", null, true);
      } else {
        styles = new Style[wmsstyles.length];
        for (int j = 0; j < styles.length; j++) {
          boolean isDefault =
              wmsstyles[j].getName().toLowerCase().indexOf("default") > -1
                  || wmsstyles[j].getName().trim().length() == 0;
          ImageURL legendURL = null;
          LegendURL[] lUrl = wmsstyles[j].getLegendURL();
          if (lUrl != null && lUrl.length > 0) {
            legendURL =
                new ImageURL(
                    lUrl[0].getWidth(),
                    lUrl[0].getHeight(),
                    lUrl[0].getFormat(),
                    lUrl[0].getOnlineResource());
          }
          styles[j] =
              new Style(
                  wmsstyles[j].getName(),
                  wmsstyles[j].getTitle(),
                  wmsstyles[j].getAbstract(),
                  legendURL,
                  isDefault);
        }
      }

      StyleList styleList = new StyleList(styles);
      BaseURL mdUrl = null;
      MetadataURL[] mdUrls = wmslay.getMetadataURL();
      if (mdUrls != null && mdUrls.length == 1 && mdUrls[0] != null) {
        mdUrl = mdUrls[0];
      }

      int authentication = LayerExtension.NONE;
      if (useAuthentification) {
        authentication = LayerExtension.USERPASSWORD;
      }
      LayerExtension lex =
          new LayerExtension(
              null,
              false,
              wmslay.getScaleHint().getMin(),
              wmslay.getScaleHint().getMax(),
              false,
              authentication,
              newNodeId,
              false,
              null);
      Layer newLay =
          new Layer(
              server,
              lay[0],
              lay[1],
              null,
              new String[] {srs},
              null,
              mdUrl,
              fl,
              styleList,
              wmslay.isQueryable(),
              false,
              lex);
      if (context
              .getLayerList()
              .getLayer(newLay.getName(), server.getOnlineResource().toExternalForm())
          == null) {
        context.getLayerList().addLayerToTop(newLay);
      }
    }
    try {
      XMLFragment xml = XMLFactory.export(context);
      System.out.println(xml.getAsPrettyString());
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }