+/*
+ * Copyright (C) 2015 Thadeu Lima de Souza Cascardo <cascardo@cascardo.eti.br>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+#include "dependente.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include <stdio.h>
+#include "cmd.h"
+#include "list.h"
+#include "util.h"
+
+void dependente_free(void *pointer)
+{
+ struct dependente *dependente = pointer;
+ if (dependente->nome)
+ free(dependente->nome);
+ if (dependente->dn)
+ free(dependente->dn);
+ if (dependente->cpf)
+ free(dependente->cpf);
+ free(dependente);
+}
+
+static struct dependente * dependente_new(char **args)
+{
+ struct dependente *dependente;
+ int r = 0;
+ dependente = malloc(sizeof(*dependente));
+ /* TODO: consertar set_int para funcionar como set_llong */
+ r += set_int(args, 2, &dependente->codigo);
+ dependente->nome = strdup(args[2]);
+ dependente->dn = strdup(args[3]);
+ dependente->cpf = strdup(args[4]);
+ if (!dependente->nome || !dependente->dn || !dependente->cpf) {
+ dependente_free(dependente);
+ return NULL;
+ }
+ if (r < 0 || dependente->codigo < 0) {
+ dependente_free(dependente);
+ return NULL;
+ }
+ return dependente;
+}
+
+static int run_dependente(struct declaracao *dec, char **args, int argc)
+{
+ struct dependente *dependente;
+ int r;
+ if (argc != 5)
+ return -EINVAL;
+ dependente = dependente_new(args);
+ if (!dependente)
+ return -ENOMEM;
+ r = list_add(&dec->dependentes, dependente);
+ if (r < 0) {
+ dependente_free(dependente);
+ return r;
+ }
+ return 0;
+}
+
+void dependente_salva(struct declaracao *dec, FILE *f)
+{
+ int i;
+ struct dependente *j;
+ for (i = 0; j = list_get(dec->dependentes, i); i++) {
+ fprintf(f, "dependente %d \"%s\" \"%s\" \"%s\"\n",
+ j->codigo, j->nome, j->dn, j->cpf);
+ }
+}
+
+static struct cmd cmd_dependente = {
+ .name = "dependente",
+ .run = run_dependente,
+};
+
+int dependente_cmd_init(void)
+{
+ cmd_add(&cmd_dependente);
+ return 0;
+}