public void insertTargets(EventModel event) throws SQLException {
    // String sql = "INSERT INTO event_targets_origins (event_id,target_origin_id,mandatory) "
    //        + " VALUES (?,?,?);";

    for (EventTarget target : event.getTargets()) {
      ContentValues values = new ContentValues();
      values.put("event_id", event.getId());
      values.put("target_origin_id", target.getTarget().getId());
      values.put("mandatory", target.isMandatory());
      // executar
      this.database.insertOrThrow("event_targets_origins", null, values);

      if (DeveloperSettings.SHOW_DAO_SQL) {
        Log.d(
            "SQL_DEBUG",
            "INSERT INTO event_targets_origins (event_id,target_origin_id,mandatory) "
                + " VALUES ("
                + event.getId()
                + ","
                + target.getTarget().getId()
                + ","
                + target.isMandatory()
                + ");");
      }
    }
  }
  private List<EventTarget> getEventTargets(EventModel event) throws SQLException {
    List<EventTarget> targets = new ArrayList();
    EventTarget target = null;
    String sql =
        "SELECT description, mandatory, target_origin_id "
            + " FROM event_targets_origins, targets_origins \n"
            + " WHERE event_id = ? AND target_origin_id = targets_origins.id;";

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

    while (cursor.moveToNext()) {
      target = new EventTarget();
      target.setTarget(
          new TargetOrigin(
              cursor.getInt(cursor.getColumnIndex("target_origin_id")),
              cursor.getString(cursor.getColumnIndex("description"))));
      target.setMandatory(cursor.getInt(cursor.getColumnIndex("mandatory")) > 0);
      target.setEvent(event);
      targets.add(target);
    }
    if (!cursor.isClosed()) {
      cursor.close();
    }
    return targets;
  }
  /**
   * 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);
        }
      }
    }
  }
  public List<EventModel> getEntityEventModels(Entity entity) 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<EventModel> events = new ArrayList();
    EventModel event = null;
    String sql =
        "SELECT events.id as event_id, model_id, events.description as event_description, synchronous, "
            + " implementation_type_id, implementation_types.description as implementation_description "
            + " FROM events, implementation_types\n"
            + " WHERE entity_id = ? AND implementation_type_id = implementation_types.id;";

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

    while (cursor.moveToNext()) {
      event = new EventModel();
      event.setId(cursor.getInt(cursor.getColumnIndex("event_id")));
      event.setDescription(cursor.getString(cursor.getColumnIndex("event_description")));
      event.setSynchronous(cursor.getInt(cursor.getColumnIndex("synchronous")) > 0);
      event.setModelId(cursor.getInt(cursor.getColumnIndex("model_id")));
      event.setEntity(entity);
      event.setImplementation(
          new Implementation(
              cursor.getInt(cursor.getColumnIndex("implementation_type_id")),
              cursor.getString(cursor.getColumnIndex("implementation_description"))));
      event.setTargets(this.getEventTargets(event));
      event.setParameters(this.getEventParameters(event));
      events.add(event);
    }
    if (!cursor.isClosed()) {
      cursor.close();
    }
    return events;
  }
  public EventModel get(int modelId, int entityModelId, int componentId) 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();
      }
    }
    EventModel event = null;
    String sql =
        "SELECT events.id as event_id, events.model_id, events.description as event_description, synchronous, \n"
            + "                implementation_type_id, implementation_types.description as implementation_description \n"
            + "                FROM events, implementation_types, entities, components \n"
            + "                WHERE events.model_id = ? AND entities.model_id = ? AND components.id = ? "
            + "                AND implementation_type_id = implementation_types.id AND entity_id = entities.id\n"
            + "                AND component_id = components.id;";

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

    if (cursor.moveToNext()) {
      event = new EventModel();
      event.setId(cursor.getInt(cursor.getColumnIndex("event_id")));
      event.setDescription(cursor.getString(cursor.getColumnIndex("event_description")));
      event.setSynchronous(cursor.getInt(cursor.getColumnIndex("synchronous")) > 0);
      event.setModelId(cursor.getInt(cursor.getColumnIndex("model_id")));
      event.setImplementation(
          new Implementation(
              cursor.getInt(cursor.getColumnIndex("implementation_type_id")),
              cursor.getString(cursor.getColumnIndex("implementation_description"))));
      event.setTargets(this.getEventTargets(event));
      event.setParameters(this.getEventParameters(event));
    }
    if (!cursor.isClosed()) {
      cursor.close();
    }
    return event;
  }
  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 void insert(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 events
    // (model_id,description,synchronous,implementation_type_id,entity_id) "
    //        + " VALUES (?,?,?,?,?);";
    event.setModelId(event.getId());
    ContentValues values = new ContentValues();
    values.put("model_id", event.getId());
    values.put("description", event.getDescription());
    values.put("synchronous", event.isSynchronous());
    values.put("implementation_type_id", event.getImplementation().getId());
    values.put("entity_id", event.getEntity().getId());

    event.setId((int) (long) this.database.insertOrThrow("events", null, values));

    if (DeveloperSettings.SHOW_DAO_SQL) {
      Log.d(
          "SQL_DEBUG",
          "INSERT INTO events (id,model_id,description,synchronous,implementation_type_id,entity_id) "
              + " VALUES ("
              + event.getId()
              + ","
              + event.getModelId()
              + ",'"
              + event.getDescription()
              + "',"
              + event.isSynchronous()
              + ","
              + event.getImplementation().getId()
              + ","
              + event.getEntity().getId()
              + ");");
    }
  }
  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;
  }