// Programación en C++ para Ingenieros, Ed. Thomson Paraninfo, 2006
// Capítulo 10: Ficheros





// Inclusión de librerías
#include <iostream>
#include <fstream>
#include <stdlib.h>

using namespace std;

typedef char id[20];
typedef char datosPers[100];

// Tipo fecha
typedef struct{
    int day, month, year;
}tFecha;

// Información del usuario
typedef struct{
    id idUsuario, clave;
    datosPers datos;
    tFecha fechaCreacion;
}tEntradaClave;


bool validar(id login, id clave)
{
    // Declaración de variables
    ifstream fClaves;
    bool acabar, idOK;
    id logAux, clAux;
    char parAux[200];

    fClaves.open("usuarios.txt");

    if (!fClaves)
    {
        cout << "No puedo abrir el fichero" << endl;
        idOK = false;
    }
    else
    {
        // acabar sirve para terminar el bucle si tenemos
        // el login correcto pero la clave es incorrecta
        acabar = false;

        // idOK nos dice si se ha entrado correctamente
        // el nombre d eusuario y la clave
        idOK = false;

        while (!fClaves.eof() && !acabar && !idOK)
        {
            fClaves.getline(logAux, 20, ':');
            fClaves.getline(clAux, 20, ':');
            fClaves.getline(parAux, 20, '\n');

            if (!strcmp(logAux, login))
                if (!strcmp(clAux, clave))
                    idOK = true;
                else
                    acabar = true;
        }
    }

    return idOK;
}


bool estaUsu(id login)
{
    ifstream fClaves;
    bool esta = false;
    id logAux;
    char parAux[250];

    fClaves.open("usuarios.txt");
    if (!fClaves)
    {
        cout << "No puedo abrir el fichero" << endl;
    }
    else
    {
        while (!fClaves.eof() && !esta)
        {
            fClaves.getline(logAux, 20, ':');
            fClaves.getline(parAux, 250, '\n');
            if (!strcmp(logAux, login))
                esta = true;
        }
    }

    return esta;
}


bool addClave(tEntradaClave& usu)
{
    bool resu, esta;
    ofstream ficheroClaves;

    esta = estaUsu(usu.idUsuario);
    if (!esta)
    {
        ficheroClaves.open("usuarios.txt", ios::app);
        if (!ficheroClaves)
        {
            cout << "No puedo abrir el fichero" << endl;
            resu = false;
        }
        else
        {
            ficheroClaves << usu.idUsuario << ':';
            ficheroClaves << usu.clave << ':';
            ficheroClaves << usu.datos << ':';
            ficheroClaves << usu.fechaCreacion.day << '-';
            ficheroClaves << usu.fechaCreacion.month << '-';
            ficheroClaves << usu.fechaCreacion.year << endl;
            resu = true;
        }
    }
    else
        resu = false;

    return resu;
}