package model;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

/**
 * Created by sarahb 
 */

public class UserBDD {

    // variable we'll use
    private static final int VERSION_BDD = 1;
    private static final String NOM_BDD = "managersBDD.db";
    private static final String TABLE_USER = "table_user";
    private static final String COL_LOGIN = "Login";
    private static final int NUM_COL_LOGIN = 0;
    private static final String COL_PWD = "Password";
    private static final int NUM_COL_PWD = 1;
    private static final String COL_NAME ="Name";
    private static final int NUM_COL_NAME = 2;
    private static final String COL_SURNAME ="Surname";
    private static final int NUM_COL_SURNAME= 3;
    private static final String COL_MAIL = "Mail";
    private static final int NUM_COL_MAIL = 4;
    private SQLiteDatabase bdd;
    private MySQLLiteBDD maBaseSQLite;

    // Cerate table and BDD
    public UserBDD(Context context) {
        maBaseSQLite = new MySQLLiteBDD(context, NOM_BDD, null, VERSION_BDD);
    }

    // open BDD
    public void open() {
        bdd = maBaseSQLite.getWritableDatabase();
    }

    // close BDD
    public void close() {
        bdd.close();
    }

    public SQLiteDatabase getBDD() {
        return bdd;
    }

  //=================================
  // Code sample for user's accounts
  //==================================

    // Create new Account
    public long insertNewUser(User user) {
        ContentValues values = new ContentValues();
        values.put(COL_LOGIN, user.getLogin());
        values.put(COL_PWD, user.getPassword());
        values.put(COL_MAIL, user.getMail());
        values.put(COL_NAME, user.getName());
        values.put(COL_SURNAME, user.getSurname());
        return bdd.insert(TABLE_USER, null, values);
    }

    // Update password
    public int updatePassword(String login, User user) {
        ContentValues values = new ContentValues();
        values.put(COL_PWD, user.getPassword());
        return bdd.update(TABLE_USER, values, COL_LOGIN + " = " + login, null);
    }

    // Verify if user exist to connect him
    public User getUserWithLogin(String login) {
        // thanks to his login
        Cursor c = bdd.query(TABLE_USER, new String[]{COL_PWD, COL_LOGIN}, COL_LOGIN + " LIKE \"" + login + "\"", null, null, null, null);
        return cursorToLivre(c);
    }

    // Convert Cursor to a User object
    private User cursorToLivre(Cursor c) {
        if (c.getCount() == 0) {
            return null;
        } else {
            c.moveToFirst();
            User user = new User();
            user.setLogin(c.getString(NUM_COL_LOGIN));
            user.setPassword(c.getString(NUM_COL_PWD));
            c.close();
            return user;
        }
    }
}