/**
   * Construct a DatabaseTableRecord whit the values of the a FermatMessage pass by parameter
   *
   * @param incomingTemplateNetworkServiceMessage the contains the values
   * @return DatabaseTableRecord whit the values
   */
  private DatabaseTableRecord constructFrom(FermatMessage incomingTemplateNetworkServiceMessage) {

    /*
     * Create the record to the entity
     */
    DatabaseTableRecord entityRecord = getDatabaseTable().getEmptyRecord();

    /*
     * Set the entity values
     */
    entityRecord.setStringValue(
        CommunicationNetworkServiceDatabaseConstants.INCOMING_MESSAGES_ID_COLUMN_NAME,
        incomingTemplateNetworkServiceMessage.getId().toString());
    entityRecord.setStringValue(
        CommunicationNetworkServiceDatabaseConstants.INCOMING_MESSAGES_SENDER_ID_COLUMN_NAME,
        incomingTemplateNetworkServiceMessage.getSender().toString());
    entityRecord.setStringValue(
        CommunicationNetworkServiceDatabaseConstants.INCOMING_MESSAGES_RECEIVER_ID_COLUMN_NAME,
        incomingTemplateNetworkServiceMessage.getReceiver().toString());
    entityRecord.setStringValue(
        CommunicationNetworkServiceDatabaseConstants.INCOMING_MESSAGES_TEXT_CONTENT_COLUMN_NAME,
        incomingTemplateNetworkServiceMessage.getContent());
    entityRecord.setStringValue(
        CommunicationNetworkServiceDatabaseConstants.INCOMING_MESSAGES_TYPE_COLUMN_NAME,
        incomingTemplateNetworkServiceMessage.getFermatMessageContentType().getCode());

    if (incomingTemplateNetworkServiceMessage.getShippingTimestamp() != null) {
      entityRecord.setLongValue(
          CommunicationNetworkServiceDatabaseConstants
              .OUTGOING_MESSAGES_SHIPPING_TIMESTAMP_COLUMN_NAME,
          incomingTemplateNetworkServiceMessage.getShippingTimestamp().getTime());
    } else {
      entityRecord.setLongValue(
          CommunicationNetworkServiceDatabaseConstants
              .OUTGOING_MESSAGES_SHIPPING_TIMESTAMP_COLUMN_NAME,
          new Long(0));
    }

    if (incomingTemplateNetworkServiceMessage.getDeliveryTimestamp() != null) {
      entityRecord.setLongValue(
          CommunicationNetworkServiceDatabaseConstants
              .INCOMING_MESSAGES_SHIPPING_TIMESTAMP_COLUMN_NAME,
          incomingTemplateNetworkServiceMessage.getDeliveryTimestamp().getTime());
    } else {
      entityRecord.setLongValue(
          CommunicationNetworkServiceDatabaseConstants
              .INCOMING_MESSAGES_DELIVERY_TIMESTAMP_COLUMN_NAME,
          new Long(0));
    }

    entityRecord.setStringValue(
        CommunicationNetworkServiceDatabaseConstants.INCOMING_MESSAGES_STATUS_COLUMN_NAME,
        incomingTemplateNetworkServiceMessage.getFermatMessagesStatus().getCode());

    /*
     * return the new table record
     */
    return entityRecord;
  }
  /**
   * This method read for new messages pending to send on the data base in the table <code>
   * outbox_messages</code> and encrypt the message content, sing the message and send it
   */
  public void processMessageToSend() {

    try {

      try {

        Map<String, Object> filters = new HashMap<>();
        filters.put(
            CommunicationNetworkServiceDatabaseConstants.OUTGOING_MESSAGES_STATUS_COLUMN_NAME,
            MessagesStatus.PENDING_TO_SEND.getCode());
        filters.put(
            CommunicationNetworkServiceDatabaseConstants.OUTGOING_MESSAGES_RECEIVER_ID_COLUMN_NAME,
            communicationsVPNConnection.getRemoteParticipant().getIdentityPublicKey());

        /*
         * Read all pending message from database
         */
        List<FermatMessage> messages = outgoingMessageDao.findAll(filters);
        /*
         * For each message
         */
        for (FermatMessage message : messages) {

          if (communicationsVPNConnection.isActive()
              && (message.getFermatMessagesStatus() != FermatMessagesStatus.SENT)) {

            /*
             * Encrypt the content of the message whit the remote network service public key
             */
            ((FermatMessageCommunication) message)
                .setContent(
                    AsymmetricCryptography.encryptMessagePublicKey(
                        message.getContent(),
                        communicationsVPNConnection
                            .getRemoteParticipantNetworkService()
                            .getIdentityPublicKey()));

            /*
             * Sing the message
             */
            String signature =
                AsymmetricCryptography.createMessageSignature(
                    message.getContent(), eccKeyPair.getPrivateKey());
            ((FermatMessageCommunication) message).setSignature(signature);

            /*
             * Send the message
             */
            communicationsVPNConnection.sendMessage(message);

            /*
             * Change the message and update in the data base
             */

            ((FermatMessageCommunication) message)
                .setFermatMessagesStatus(FermatMessagesStatus.SENT);
            outgoingMessageDao.update(message);

            /*
             * Put the message on a event and fire new event
             */
            FermatEvent fermatEvent =
                eventManager.getNewEvent(
                    P2pEventType.NEW_NETWORK_SERVICE_MESSAGE_SENT_NOTIFICATION);
            fermatEvent.setSource(AssetIssuerActorNetworkServicePluginRoot.EVENT_SOURCE);
            ((NewNetworkServiceMessageSentNotificationEvent) fermatEvent).setData(message);
            eventManager.raiseEvent(fermatEvent);
          }
        }

      } catch (CantUpdateRecordDataBaseException e) {
        errorManager.reportUnexpectedPluginException(
            Plugins.BITDUBAI_DAP_ASSET_ISSUER_ACTOR_NETWORK_SERVICE,
            UnexpectedPluginExceptionSeverity.DISABLES_SOME_FUNCTIONALITY_WITHIN_THIS_PLUGIN,
            new Exception("Can not process messages to send. Error reason: " + e.getMessage()));
      } catch (CantReadRecordDataBaseException e) {
        errorManager.reportUnexpectedPluginException(
            Plugins.BITDUBAI_DAP_ASSET_ISSUER_ACTOR_NETWORK_SERVICE,
            UnexpectedPluginExceptionSeverity.DISABLES_SOME_FUNCTIONALITY_WITHIN_THIS_PLUGIN,
            new Exception("Can not process messages to send. Error reason: " + e.getMessage()));
      }

      // Sleep for a time
      toSend.sleep(CommunicationNetworkServiceRemoteAgent.SLEEP_TIME);

    } catch (InterruptedException e) {
      errorManager.reportUnexpectedPluginException(
          Plugins.BITDUBAI_DAP_ASSET_ISSUER_ACTOR_NETWORK_SERVICE,
          UnexpectedPluginExceptionSeverity.DISABLES_SOME_FUNCTIONALITY_WITHIN_THIS_PLUGIN,
          new Exception("Can not sleep"));
    }
  }