/**
   * (no-javadoc)
   *
   * @see FermatPacketProcessor#processingPackage(FermatPacket)
   */
  @Override
  public void processingPackage(FermatPacket receiveFermatPacket) {

    /*
     * Get the filters from the message content and decrypt
     */
    String messageContentJsonStringRepresentation =
        AsymmetricCryptography.decryptMessagePrivateKey(
            receiveFermatPacket.getMessageContent(),
            getWsCommunicationsCloudClientChannel().getClientIdentity().getPrivateKey());

    // System.out.println("FailureComponentRegistrationRequestPacketProcessor -
    // messageContentJsonStringRepresentation = "+messageContentJsonStringRepresentation);

    /*
     * Construct the json object
     */
    JsonObject packetContent =
        jsonParser.parse(messageContentJsonStringRepresentation).getAsJsonObject();
    NetworkServiceType networkServiceApplicant =
        gson.fromJson(
            packetContent.get(JsonAttNamesConstants.NETWORK_SERVICE_TYPE).getAsString(),
            NetworkServiceType.class);
    PlatformComponentProfile platformComponentProfile =
        new PlatformComponentProfileCommunication()
            .fromJson(packetContent.get(JsonAttNamesConstants.PROFILE_TO_REGISTER).getAsString());
    String errorMsj = packetContent.get(JsonAttNamesConstants.FAILURE_VPN_MSJ).getAsString();

    System.out.println("FailureComponentRegistrationRequestPacketProcessor - errorMsj " + errorMsj);

    /*
     * Create a new event whit the networkServiceType and remoteIdentity
     */
    FermatEvent event =
        P2pEventType.FAILURE_COMPONENT_REGISTRATION_REQUEST_NOTIFICATION.getNewEvent();
    event.setSource(EventSource.WS_COMMUNICATION_CLOUD_CLIENT_PLUGIN);

    /*
     * Configure the values
     */
    ((FailureComponentRegistrationNotificationEvent) event)
        .setNetworkServiceApplicant(networkServiceApplicant);
    ((FailureComponentRegistrationNotificationEvent) event)
        .setPlatformComponentProfile(platformComponentProfile);
    ((FailureComponentRegistrationNotificationEvent) event).setErrorMsj(errorMsj);

    /*
     * Raise the event
     */
    // System.out.println("FailureComponentRegistrationRequestPacketProcessor - Raised a event =
    // P2pEventType.FAILURE_COMPONENT_REGISTRATION_REQUEST_NOTIFICATION");
    getWsCommunicationsCloudClientChannel().getEventManager().raiseEvent(event);
  }
  /**
   * Validate the signature of the packet
   *
   * @param fermatPacketReceive
   */
  private void validateFermatPacketSignature(FermatPacket fermatPacketReceive) {

    System.out.println(" WsCommunicationsTyrusCloudClientChannel - validateFermatPacketSignature");

    /*
     * Validate the signature
     */
    boolean isValid =
        AsymmetricCryptography.verifyMessageSignature(
            fermatPacketReceive.getSignature(),
            fermatPacketReceive.getMessageContent(),
            getServerIdentity());

    // System.out.println(" WsCommunicationsTyrusCloudClientChannel - isValid = " + isValid);

    /*
     * if not valid signature
     */
    if (!isValid) {
      throw new RuntimeException(
          "Fermat Packet received has not a valid signature, go to close this connection maybe is compromise");
    }
  }
  /**
   * (no-javadoc)
   *
   * @see FermatTyrusPacketProcessor#processingPackage(FermatPacket)
   */
  @Override
  public void processingPackage(FermatPacket receiveFermatPacket) {

    // System.out.println(" ---------------------------------------------------------------------
    // ");
    // System.out.println("ComponentConnectionRespondTyrusPacketProcessor - Starting
    // processingPackage");

    /*
     * Get the message content and decrypt
     */
    String messageContentJsonStringRepresentation =
        AsymmetricCryptography.decryptMessagePrivateKey(
            receiveFermatPacket.getMessageContent(),
            getWsCommunicationsTyrusCloudClientChannel().getClientIdentity().getPrivateKey());

    // System.out.println("ComponentConnectionRespondTyrusPacketProcessor -
    // messageContentJsonStringRepresentation = "+messageContentJsonStringRepresentation);

    try {

      /*
       * Construct the json object
       */
      Gson gson = new Gson();
      JsonParser parser = new JsonParser();
      JsonObject respond = parser.parse(messageContentJsonStringRepresentation).getAsJsonObject();

      // Get all values
      URI vpnServerUri = new URI(respond.get(JsonAttNamesConstants.VPN_URI).getAsString());
      String vpnServerIdentity =
          respond.get(JsonAttNamesConstants.VPN_SERVER_IDENTITY).getAsString();
      PlatformComponentProfile participantVpn =
          gson.fromJson(
              respond.get(JsonAttNamesConstants.APPLICANT_PARTICIPANT_VPN).getAsString(),
              PlatformComponentProfileCommunication.class);
      PlatformComponentProfile remotePlatformComponentProfile =
          gson.fromJson(
              respond.get(JsonAttNamesConstants.REMOTE_PARTICIPANT_VPN).getAsString(),
              PlatformComponentProfileCommunication.class);
      PlatformComponentProfile remoteNsPlatformComponentProfile =
          gson.fromJson(
              respond.get(JsonAttNamesConstants.REMOTE_PARTICIPANT_NS_VPN).getAsString(),
              PlatformComponentProfileCommunication.class);

      /*
       * get the Server ip and port
       */
      String ServerIp =
          getWsCommunicationsTyrusCloudClientChannel()
              .getWsCommunicationsTyrusCloudClientConnection()
              .getServerIp();
      Integer ServerPort =
          getWsCommunicationsTyrusCloudClientChannel()
              .getWsCommunicationsTyrusCloudClientConnection()
              .getServerPort();

      vpnServerUri = new URI(ServerConf.WS_PROTOCOL + ServerIp + ":" + ServerPort + vpnServerUri);

      System.out.println(
          "ComponentConnectionRespondTyrusPacketProcessor - vpnServerUri to connect = "
              + vpnServerUri);

      /*
       * Get the  wsCommunicationVPNClientManagerAgent
       */
      WsCommunicationTyrusVPNClientManagerAgent wsCommunicationTyrusVPNClientManagerAgent =
          WsCommunicationTyrusVPNClientManagerAgent.getInstance();

      /*
       * Create a new VPN client
       */
      wsCommunicationTyrusVPNClientManagerAgent.createNewWsCommunicationVPNClient(
          vpnServerUri,
          vpnServerIdentity,
          participantVpn,
          remotePlatformComponentProfile,
          remoteNsPlatformComponentProfile,
          getWsCommunicationsTyrusCloudClientChannel().getEventManager());

    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  @OnMessage
  public void onMessage(String fermatPacketEncode) {

    System.out.println(" --------------------------------------------------------------------- ");
    System.out.println(
        " WsCommunicationsTyrusCloudClientChannel - Starting method onMessage(String)");
    // System.out.println(" WsCommunicationsTyrusCloudClientChannel - encode fermatPacket " +
    // fermatPacketEncode);

    FermatPacket fermatPacketReceive = null;

    /*
     * If the client is no register
     */
    if (!isRegister) {

      System.out.println(
          " WsCommunicationsTyrusCloudClientChannel - decoding fermatPacket with temp-identity ");

      /** Decode the message with the temporal identity */
      fermatPacketReceive =
          FermatPacketDecoder.decode(fermatPacketEncode, temporalIdentity.getPrivateKey());

    } else {

      System.out.println(
          " WsCommunicationsTyrusCloudClientChannel - decoding fermatPacket with client-identity ");

      /** Decode the message with the client identity */
      fermatPacketReceive =
          FermatPacketDecoder.decode(fermatPacketEncode, clientIdentity.getPrivateKey());

      /*
       * Validate the signature
       */
      validateFermatPacketSignature(fermatPacketReceive);
    }

    // System.out.println(" WsCommunicationsTyrusCloudClientChannel - decode fermatPacket " +
    // fermatPacketReceive.toJson());

    // verify is packet supported
    if (packetProcessorsRegister.containsKey(fermatPacketReceive.getFermatPacketType())) {

      /*
       * Call the processors for this packet
       */
      for (FermatTyrusPacketProcessor fermatPacketProcessor :
          packetProcessorsRegister.get(fermatPacketReceive.getFermatPacketType())) {

        /*
         * Processor make his job
         */
        fermatPacketProcessor.processingPackage(fermatPacketReceive);
      }

    } else {

      System.out.println(
          " WsCommunicationsTyrusCloudClientChannel - Packet type "
              + fermatPacketReceive.getFermatPacketType()
              + "is not supported");
    }
  }
  /**
   * (no-javadoc)
   *
   * @see FermatTyrusPacketProcessor#processingPackage(FermatPacket)
   */
  @Override
  public void processingPackage(final FermatPacket receiveFermatPacket) {

    // System.out.println(" ---------------------------------------------------------------------
    // ");
    // System.out.println("ServerHandshakeRespondTyrusPacketProcessor - processingPackage");

    /* -----------------------------------------------------------------------------------------
     * IMPORTANT: This Message Content of this packet come encrypted with the temporal identity public key
     * and contain the server identity whit the communications cloud client that
     * have to use to talk with the server.
     * -----------------------------------------------------------------------------------------
     */

    /*
     * Decrypt the message content
     */
    String jsonRepresentation =
        AsymmetricCryptography.decryptMessagePrivateKey(
            receiveFermatPacket.getMessageContent(),
            getWsCommunicationsTyrusCloudClientChannel().getTemporalIdentity().getPrivateKey());

    /*
     * Construct the json object
     */
    JsonParser parser = new JsonParser();
    JsonObject serverIdentity = parser.parse(jsonRepresentation).getAsJsonObject();

    /*
     * Get the server identity and set into the communication cloud client
     */
    getWsCommunicationsTyrusCloudClientChannel()
        .setServerIdentity(serverIdentity.get(JsonAttNamesConstants.SERVER_IDENTITY).getAsString());

    // System.out.println("ServerHandshakeRespondTyrusPacketProcessor - ServerIdentity = "+
    // getWsCommunicationsTyrusCloudClientChannel().getServerIdentity());

    /*
     * Construct a Communications Cloud Client Profile for this component and send and fermat packet type FermatPacketType.COMPONENT_REGISTRATION_REQUEST
     */

    HardwareManager hardwareManager =
        getWsCommunicationsTyrusCloudClientChannel().getHardwareManager();
    CloudClientExtraData cloudClientExtraData = null;
    if (hardwareManager != null) {
      cloudClientExtraData =
          new CloudClientExtraData(
              hardwareManager.getOperativeSystem(),
              hardwareManager.getBoard(),
              hardwareManager.getBrand(),
              hardwareManager.getDevice());
    }

    PlatformComponentProfile communicationsCloudClientProfile =
        getWsCommunicationsTyrusCloudClientChannel()
            .getWsCommunicationsTyrusCloudClientConnection()
            .constructPlatformComponentProfileFactory(
                getWsCommunicationsTyrusCloudClientChannel().getClientIdentity().getPublicKey(),
                "WsCommunicationsCloudClientChannel",
                "Web Socket Communications Cloud Client",
                NetworkServiceType.UNDEFINED,
                PlatformComponentType.COMMUNICATION_CLOUD_CLIENT,
                (hardwareManager != null) ? new Gson().toJson(cloudClientExtraData) : null);
    getWsCommunicationsTyrusCloudClientChannel()
        .setPlatformComponentProfile(communicationsCloudClientProfile);

    /* ------------------------------------
     * IMPORTANT: At this moment the server only
     * know the temporal identity of the client
     * the packet has construct with this identity
     * --------------------------------------
     */

    /*
     * Construc the jsonObject
     */
    Gson gson = new Gson();
    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty(
        JsonAttNamesConstants.NETWORK_SERVICE_TYPE, NetworkServiceType.UNDEFINED.toString());
    jsonObject.addProperty(
        JsonAttNamesConstants.PROFILE_TO_REGISTER, communicationsCloudClientProfile.toJson());

    /*
     * Construct a fermat packet whit the server identity
     */
    FermatPacket fermatPacketRespond =
        FermatPacketCommunicationFactory.constructFermatPacketEncryptedAndSinged(
            getWsCommunicationsTyrusCloudClientChannel().getServerIdentity(), // Destination
            getWsCommunicationsTyrusCloudClientChannel()
                .getTemporalIdentity()
                .getPublicKey(), // Sender
            gson.toJson(jsonObject), // Message Content
            FermatPacketType.COMPONENT_REGISTRATION_REQUEST, // Packet type
            getWsCommunicationsTyrusCloudClientChannel()
                .getTemporalIdentity()
                .getPrivateKey()); // Sender private key

    /*
     * Send the encode packet to the server
     */
    getWsCommunicationsTyrusCloudClientChannel()
        .sendMessage(FermatPacketEncoder.encode(fermatPacketRespond));
  }