#include "headers/Customer.h"


// constructors
Customer::Customer(string name_, string password_, Vehicle_type vehicle_, string telephone_)
    : id{auto_increment_db() + 1},
      name{name_},
      password{hash_password(password_)},
      vehicle{vehicle_},
      telephone{telephone_} {
    save_db();
}

Customer::Customer(int id_, string name_, string password_, Vehicle_type vehicle_,
                   vector<Park_time> instances, string telephone_)
    : id{id_},
      name{name_},
      password{password_},
      vehicle{vehicle_},
      park_instances{instances},
      telephone{telephone_} {}

// clock in/out methods
// ====================================================================================
/*
Create a p_time object with start=now and adds to vector
 */
void Customer::clock_in(int s_id) {
    Park_time pt{id, s_id};
    park_instances.push_back(pt);
}

// edit last p_time object so end=now
void Customer::clock_out(int s_id) {
    park_instances[park_instances.size() - 1].clock_out(id, s_id);
}

bool Customer::parked() {
    if (!park_instances.size()) {
        return false;
    }
    if ((park_instances[park_instances.size() - 1].duration)) {
        // if duration of the last parktime == 0, meaning
        // that the customer has not clocked out
        return false;
    } else {
        return true;
    }
}

int Customer::parked_at() { return park_instances[park_instances.size() - 1].spot_id; }

//================================================================================================
// functions that interact with the database

void Customer::save_db() {
    string statement{"insert into Customer values (, '', '', ,'');"};
    // after ( = 28)
    statement.insert(41, telephone);
    statement.insert(38, to_string(int(vehicle)));
    statement.insert(36, password);
    statement.insert(32, name);
    statement.insert(29, to_string(id));
    // cout << statement;
    SQLite::Transaction transaction(data::db);
    data::db.exec(statement);
    transaction.commit();
}

void Customer::update_db() {
    string statement =
        "UPDATE Customer SET name = '', password = '', "
        "vehicle = '', telephone = '' where id = '';";
    statement.insert(87, to_string(id));
    statement.insert(73, telephone);
    statement.insert(57, to_string(int(vehicle)));
    statement.insert(43, password);
    statement.insert(28, name);
    // cout << statement;
    data::db.exec(statement);
}

void Customer::delete_db() {
    string statement = "delete from Customer where id= ;";
    statement.insert(statement.length() - 2, to_string(id));
    SQLite::Transaction transaction(data::db);
    data::db.exec(statement);
    transaction.commit();
}

int Customer::auto_increment_db() {
    SQLite::Statement max_id(data::db, "select max(id) from Customer;");
    int id = 0;
    max_id.executeStep();
    id = max_id.getColumn(0);
    max_id.reset();
    return id;
}
