public Content getLastEventContentByLabelAndValue(
      Object value, String label, int eventModelId, int entityModelId, int componentModelId)
      throws SQLException, Exception {
    Content content = null;
    String sql =
        " SELECT event_contents.id as id, reading_value, time "
            + " FROM  generated_events, event_contents , event_parameters, events "
            + " WHERE reading_value = ? AND parameter_label = ? AND events.model_id = ? AND generated_events.entity_id = ? AND component_id = ? "
            + " AND generated_event_id = generated_events.id AND event_parameter_id = event_parameters.id AND events.id = generated_events.event_id "
            + " ORDER BY time DESC LIMIT 1;";

    Cursor cursor =
        this.database.rawQuery(
            sql,
            new String[] {
              String.valueOf(value),
              String.valueOf(label),
              String.valueOf(eventModelId),
              String.valueOf(entityModelId),
              String.valueOf(componentModelId)
            });

    if (cursor.moveToNext()) {
      content = new Content();
      content.setTime(new Date(cursor.getLong(cursor.getColumnIndex("time"))));
      content.setId(cursor.getInt(cursor.getColumnIndex("id")));
      content.setValue(value);
    }
    if (!cursor.isClosed()) {
      cursor.close();
    }
    return content;
  }
  public Content getCurrentContentValue(Parameter parameter) throws SQLException {
    if (this.database == null || !this.database.isOpen()) {
      try {
        this.database = (SQLiteDatabase) dataManager.getDatabaseHelper().openDatabaseConnection();
      } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    Content content = null;
    String sql =
        "SELECT id, reading_value, reading_time "
            + "FROM event_contents\n"
            + "WHERE event_parameter_id = ? ORDER BY id DESC LIMIT 1;";

    // consulta
    Cursor cursor = this.database.rawQuery(sql, new String[] {String.valueOf(parameter.getId())});

    if (cursor.moveToFirst()) {
      content = new Content();
      // pegar o valor atual
      content.setId(cursor.getInt(cursor.getColumnIndex("id")));
      content.setTime(
          new Date(Long.parseLong(cursor.getString(cursor.getColumnIndex("reading_time")))));
      content.setValue(
          Content.parseContent(
              parameter.getDataType(), cursor.getString(cursor.getColumnIndex("reading_value"))));
    }
    if (!cursor.isClosed()) {
      cursor.close();
    }
    return content;
  }
  /**
   * @param parameter
   * @throws SQLException
   */
  public void insertPossibleParameterContents(Parameter parameter) throws SQLException {
    if (this.database == null || !this.database.isOpen()) {
      try {
        this.database = (SQLiteDatabase) dataManager.getDatabaseHelper().openDatabaseConnection();
      } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    // String sql = "INSERT INTO possible_event_contents (possible_value, default_value,
    // event_parameter_id) "
    //        + " VALUES (?,?,?);";

    if (parameter.getPossibleContents() != null) {
      for (PossibleContent possibleContent : parameter.getPossibleContents()) {
        // valores
        ContentValues values = new ContentValues();
        values.put(
            "possible_value",
            String.valueOf(
                Content.parseContent(parameter.getDataType(), possibleContent.getValue())));
        values.put("default_value", possibleContent.isIsDefault());
        values.put("event_parameter_id", parameter.getId());
        // executar
        possibleContent.setId(
            (int) (long) this.database.insertOrThrow("possible_event_contents", null, values));

        if (DeveloperSettings.SHOW_DAO_SQL) {
          Log.d(
              "SQL_DEBUG",
              "INSERT INTO possible_event_contents (id,possible_value, default_value, event_parameter_id) "
                  + " VALUES ("
                  + possibleContent.getId()
                  + ","
                  + Content.parseContent(parameter.getDataType(), possibleContent.getValue())
                  + ","
                  + possibleContent.isIsDefault()
                  + ","
                  + parameter.getId()
                  + ");");
        }
      }
    }
  }
  public void insertContent(Parameter parameter, Event event) throws SQLException {
    if (this.database == null || !this.database.isOpen()) {
      try {
        this.database = (SQLiteDatabase) dataManager.getDatabaseHelper().openDatabaseConnection();
      } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    // String sql = "INSERT INTO event_contents (reading_value,reading_time,event_parameter_id,
    // generated_event_id) "
    //        + " VALUES (?,?,?,?);";

    ContentValues values = new ContentValues();
    values.put(
        "reading_value",
        String.valueOf(
            Content.parseContent(parameter.getDataType(), parameter.getContent().getValue())));
    values.put("reading_time", parameter.getContent().getTime().getTime());
    values.put("event_parameter_id", parameter.getId());
    values.put("generated_event_id", event.getDatabaseId());
    // executar
    parameter
        .getContent()
        .setId((int) (long) this.database.insertOrThrow("event_contents", null, values));

    if (DeveloperSettings.SHOW_DAO_SQL) {
      Log.d(
          "SQL_DEBUG",
          "INSERT INTO event_contents (id,reading_value,reading_time,event_parameter_id) "
              + " VALUES ("
              + parameter.getContent().getId()
              + ",'"
              + Content.parseContent(parameter.getDataType(), parameter.getContent().getValue())
              + "',"
              + ",'"
              + parameter.getContent().getTime().getTime()
              + "',"
              + ","
              + parameter.getId()
              + ");");
    }
  }
  /**
   * Gera o evento e salva o valor do parâmetros. Se algum parâmetro obrigatório estiver com valor
   * nulo é gerada uma exceção.
   *
   * @param event
   * @param eventModel
   * @throws SQLException
   * @throws Exception
   */
  public void insert(Event event, EventModel eventModel) throws SQLException, Exception {
    if (this.database == null || !this.database.isOpen()) {
      try {
        this.database = (SQLiteDatabase) dataManager.getDatabaseHelper().openDatabaseConnection();
      } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    // Criar evento
    // String sql = "INSERT INTO generated_events
    // (event_id,entity_id,component_id,time,timeout,event_type) "
    //        + " VALUES (?,?,?,?,?,?);";
    ContentValues values = new ContentValues();
    values.put("event_id", eventModel.getId());
    values.put("entity_id", event.getEntityId());
    values.put("component_id", event.getComponentManager().getComponentId());
    values.put("time", event.getTime().getTime());
    values.put("timeout", event.getTimeout());
    values.put("event_type", event.getEventType());

    event.setDatabaseId((int) (long) this.database.insertOrThrow("generated_events", null, values));

    // adicionar conteúdos dos parâmetros
    for (Parameter p : eventModel.getParameters()) {
      if (event.getParameters().get(p.getLabel()) == null && !p.isOptional()) {
        throw new Exception(
            "Parameter "
                + p.getLabel()
                + " from the event "
                + eventModel.getDescription()
                + " id "
                + eventModel.getId()
                + " was not found. Such parameter is not optional!");
      } else {
        if (event.getParameters().get(p.getLabel()) != null) {
          p.setContent(
              new Content(
                  Content.parseContent(p.getDataType(), event.getParameters().get(p.getLabel())),
                  event.getTime()));
          this.insertContent(p, event);
        }
      }
    }
  }
  private List<PossibleContent> getPossibleContents(Parameter parameter) throws SQLException {
    List<PossibleContent> possibleContents = new ArrayList();
    String sql =
        " SELECT id, possible_value, default_value "
            + " FROM possible_event_contents\n"
            + " WHERE event_parameter_id = ?;";

    Cursor cursor = this.database.rawQuery(sql, new String[] {String.valueOf(parameter.getId())});

    while (cursor.moveToNext()) {
      possibleContents.add(
          new PossibleContent(
              cursor.getInt(cursor.getColumnIndex("id")),
              Content.parseContent(
                  parameter.getDataType(),
                  cursor.getString(cursor.getColumnIndex("possible_value"))),
              cursor.getInt(cursor.getColumnIndex("default_value")) > 0));
    }
    if (!cursor.isClosed()) {
      cursor.close();
    }
    return possibleContents;
  }
  public void insertParameters(EventModel event) throws SQLException {
    if (this.database == null || !this.database.isOpen()) {
      try {
        this.database = (SQLiteDatabase) dataManager.getDatabaseHelper().openDatabaseConnection();
      } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    // String sql = "INSERT INTO event_parameters
    // (description,optional,parameter_label,superior_limit,inferior_limit,initial_value,entity_state_id,data_type_id,event_id) "
    //        + " VALUES (?,?,?,?,?,?,?,?,?);";

    if (event.getParameters() != null) {
      for (Parameter parameter : event.getParameters()) {
        ContentValues values = new ContentValues();
        // trata o tipo de dado do estado
        parameter.setSuperiorLimit(
            Content.parseContent(parameter.getDataType(), parameter.getSuperiorLimit()));
        parameter.setInferiorLimit(
            Content.parseContent(parameter.getDataType(), parameter.getInferiorLimit()));
        parameter.setInitialValue(
            Content.parseContent(parameter.getDataType(), parameter.getInitialValue()));
        // valores
        values.put("description", parameter.getDescription());
        values.put("optional", parameter.isOptional());
        values.put("parameter_label", parameter.getLabel());
        values.put("superior_limit", String.valueOf(parameter.getSuperiorLimit()));
        values.put("inferior_limit", String.valueOf(parameter.getInferiorLimit()));
        values.put("initial_value", String.valueOf(parameter.getInitialValue()));
        values.put(
            "entity_state_id",
            (parameter.getRelatedState() == null) ? -1 : parameter.getRelatedState().getId());
        values.put("data_type_id", parameter.getDataType().getId());
        values.put("event_id", event.getId());
        // executar
        parameter.setId((int) (long) this.database.insertOrThrow("event_parameters", null, values));

        if (DeveloperSettings.SHOW_DAO_SQL) {
          Log.d(
              "SQL_DEBUG",
              "INSERT INTO event_parameters (id,description,optional,parameter_label,superior_limit,inferior_limit,initial_value,entity_state_id,data_type_id,event_id) "
                  + " VALUES ("
                  + parameter.getId()
                  + ",'"
                  + parameter.getDescription()
                  + "','"
                  + parameter.getLabel()
                  + "','"
                  + parameter.getSuperiorLimit()
                  + "','"
                  + parameter.getInferiorLimit()
                  + "','"
                  + parameter.getInitialValue()
                  + "',"
                  + ((parameter.getRelatedState() == null)
                      ? -1
                      : parameter.getRelatedState().getId())
                  + ","
                  + parameter.getDataType().getId()
                  + ","
                  + event.getId()
                  + ");");
        }
      }
    }
  }
  public List<Parameter> getEventParameterContents(int dataBaseEventId) throws SQLException {
    List<Parameter> parameters = new ArrayList();
    Parameter parameter;
    Content content;
    String sql =
        "SELECT event_contents.id as content_id, reading_value, reading_time, event_parameters.id as parameter_id, "
            + " parameter_label as label, event_parameters.description as parameter_desc, optional, superior_limit, "
            + " inferior_limit, entity_state_id, event_parameters.initial_value, data_type_id, "
            + " data_types.initial_value as data_initial_value, data_types.description as data_desc "
            + " FROM event_contents, event_parameters, data_types "
            + " WHERE generated_event_id = ?  AND event_parameter_id = event_parameters.id AND data_types.id = data_type_id "
            + " ORDER BY generated_event_id ; ";

    Cursor cursor = this.database.rawQuery(sql, new String[] {String.valueOf(dataBaseEventId)});

    while (cursor.moveToNext()) {
      parameter = new Parameter();
      parameter.setId(cursor.getInt(cursor.getColumnIndex("parameter_id")));
      parameter.setDescription(cursor.getString(cursor.getColumnIndex("parameter_desc")));
      parameter.setLabel(cursor.getString(cursor.getColumnIndex("label")));
      DataType type = new DataType();
      type.setId(cursor.getInt(cursor.getColumnIndex("data_type_id")));
      type.setDescription(cursor.getString(cursor.getColumnIndex("data_desc")));
      type.setInitialValue(cursor.getString(cursor.getColumnIndex("data_initial_value")));
      parameter.setDataType(type);
      // trata o tipo de dado do estado
      parameter.setSuperiorLimit(
          Content.parseContent(parameter.getDataType(), parameter.getSuperiorLimit()));
      parameter.setInferiorLimit(
          Content.parseContent(parameter.getDataType(), parameter.getInferiorLimit()));
      parameter.setInitialValue(
          Content.parseContent(parameter.getDataType(), parameter.getInitialValue()));
      parameter.setInferiorLimit(
          Content.parseContent(type, cursor.getString(cursor.getColumnIndex("inferior_limit"))));
      parameter.setSuperiorLimit(
          Content.parseContent(type, cursor.getString(cursor.getColumnIndex("superior_limit"))));
      parameter.setInitialValue(
          Content.parseContent(type, cursor.getString(cursor.getColumnIndex("initial_value"))));
      parameter.setOptional(cursor.getInt(cursor.getColumnIndex("optional")) > 0);
      if (cursor.getInt(cursor.getColumnIndex("entity_state_id")) > 0) {
        if (this.dataManager == null) {
          EntityStateDAO dao = new EntityStateDAO(this.database);
          parameter.setRelatedState(
              dao.getState(cursor.getInt(cursor.getColumnIndex("entity_state_id"))));
        } else {
          parameter.setRelatedState(
              this.dataManager
                  .getEntityStateDAO()
                  .getState(cursor.getInt(cursor.getColumnIndex("entity_state_id"))));
        }
      }
      // pega o valor utilizado na ação
      content = new Content();
      content.setId(cursor.getInt(cursor.getColumnIndex("content_id")));
      content.setTime(
          new Date(Long.parseLong(cursor.getString(cursor.getColumnIndex("reading_time")))));
      content.setValue(
          Content.parseContent(
              parameter.getDataType(), cursor.getString(cursor.getColumnIndex("reading_value"))));
      parameter.setContent(content);

      parameter.setPossibleContents(this.getPossibleContents(parameter));
      parameters.add(parameter);
    }
    if (!cursor.isClosed()) {
      cursor.close();
    }
    return parameters;
  }
  private List<Parameter> getEventParameters(EventModel event) throws SQLException {
    if (this.database == null || !this.database.isOpen()) {
      try {
        this.database = (SQLiteDatabase) dataManager.getDatabaseHelper().openDatabaseConnection();
      } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    List<Parameter> parameters = new ArrayList();
    Parameter parameter = null;
    String sql =
        "SELECT event_parameters.id as parameter_id, parameter_label, event_parameters.description as parameter_desc, \n"
            + "                optional, superior_limit, inferior_limit, entity_state_id,\n"
            + "                event_parameters.initial_value, data_type_id, data_types.initial_value as data_initial_value,\n"
            + "                data_types.description as data_desc\n"
            + "                FROM event_parameters, data_types\n"
            + "                WHERE event_id = ? and data_types.id = data_type_id;";

    Cursor cursor = this.database.rawQuery(sql, new String[] {String.valueOf(event.getId())});

    while (cursor.moveToNext()) {
      parameter = new Parameter();
      parameter.setId(cursor.getInt(cursor.getColumnIndex("parameter_id")));
      parameter.setDescription(cursor.getString(cursor.getColumnIndex("parameter_desc")));
      parameter.setLabel(cursor.getString(cursor.getColumnIndex("parameter_label")));
      DataType type = new DataType();
      type.setId(cursor.getInt(cursor.getColumnIndex("data_type_id")));
      type.setDescription(cursor.getString(cursor.getColumnIndex("data_desc")));
      type.setInitialValue(cursor.getString(cursor.getColumnIndex("data_initial_value")));
      parameter.setDataType(type);
      parameter.setInferiorLimit(
          Content.parseContent(type, cursor.getString(cursor.getColumnIndex("inferior_limit"))));
      parameter.setSuperiorLimit(
          Content.parseContent(type, cursor.getString(cursor.getColumnIndex("superior_limit"))));
      parameter.setInitialValue(
          Content.parseContent(type, cursor.getString(cursor.getColumnIndex("initial_value"))));
      parameter.setOptional(cursor.getInt(cursor.getColumnIndex("optional")) > 0);
      if (cursor.getInt(cursor.getColumnIndex("entity_state_id")) > 0) {
        if (this.dataManager == null) {
          EntityStateDAO dao = new EntityStateDAO(this.database);
          parameter.setRelatedState(
              dao.getState(cursor.getInt(cursor.getColumnIndex("entity_state_id"))));
        } else {
          parameter.setRelatedState(
              this.dataManager
                  .getEntityStateDAO()
                  .getState(cursor.getInt(cursor.getColumnIndex("entity_state_id"))));
        }
      }

      // pegar o valor atual
      Content c = this.getCurrentContentValue(parameter);
      if (c
          != null) { // se c for nulo deve usar os valores iniciais, senão adiciona o conteúdo no
                     // estado
        parameter.setContent(c);
      }
      parameters.add(parameter);
    }
    if (!cursor.isClosed()) {
      cursor.close();
    }
    return parameters;
  }