#include "databaselms.h"

#include <QtSql>
#include <QSqlDatabase>
#include <QSqlDriver>
#include <QMessageBox>


QList<Group> DataBaseLMS::selectAllGroups()
{
    QList<Group> listGroups;

    QString queryStr = QString("SELECT group_id, name "
                                                 "FROM public.groups "
                                                 "ORDER BY group_id ASC");

    QSqlQuery query = QSqlQuery(*db);

    if(queryExec(queryStr, &query))
    {
        while (query.next())
        {//Группа
            Group group;
            group.setID(query.value(0).toInt());
            group.setName(query.value(1).toString());

            listGroups.append(group);
        }
    }

    return listGroups;
}

Group DataBaseLMS::selectGroup(int id_group)
{
    Group group;

    QString queryStr = QString("SELECT group_id, name "
                                                 "FROM public.groups "
                                                 "WHERE groups.group_id = %1 ").arg(
                                                        id_group);

    QSqlQuery query = QSqlQuery(*db);

    if(queryExec(queryStr, &query))
    {
        if (query.first())
        {//Инструктор
            group.setID(query.value(0).toInt());
            group.setName(query.value(1).toString());
        }
    }

    return group;
}

int DataBaseLMS::insertGroup()
{
    QString queryStr = QString("INSERT INTO public.groups "
                                                 "DEFAULT VALUES "
                                                 "RETURNING group_id");

    return queryExecInt(queryStr);
}

int DataBaseLMS::insertGroup(Group group)
{
    QString queryStr = QString("INSERT INTO public.groups (name) "
                                                 "VALUES ('%1') "
                                                 "RETURNING groups.group_id").arg(
                                                        group.getName());

    return queryExecInt(queryStr);
}

int DataBaseLMS::deleteGroup(int id_group)
{
    QString queryStr = QString("DELETE FROM public.groups "
                                                 "WHERE group_id = %1 "
                                                 "RETURNING groups.group_id").arg(
                                                        QString::number(id_group));

    return queryExecInt(queryStr);
}

int DataBaseLMS::updateGroup(Group group)
{
    QString queryStr = QString("UPDATE public.groups SET name = '%1' "
                                                 "WHERE group_id = %2 "
                                                 "RETURNING groups.group_id").arg(
                                                        group.getName(),
                                                        QString::number(group.getID()) );

    return queryExecInt(queryStr);
}
