//
// Created by zhang on 2024/12/29.
//
#include <stdio.h>
#include <stdbool.h>
#include <windows.h>
#include "./include/function.h"
#include "./include/extern.h"
#include "./include/curses.h"
#include "./include/sqlite3.h"
extern char Username[15];
extern char class[15];
void myexit() {
    endwin();
    exit(0);
}

void Login(char *username,char*password,int *recall,char *errmsg){
    if(!username[0]){
        strcpy(errmsg,"The username is empty!");
        *recall=-1;
        return;
    }
    if(!password[0]){
        strcpy(errmsg,"The password is empty!");
        *recall=-1;
        return;
    }
    sqlite3 *db;
    int rc;

    // 打开数据库
    rc = sqlite3_open("./data/msg.db", &db);
    if (rc) {
        strcpy(errmsg,"Error:database error.");
        *recall=-1;
        return;
    }

    // SQL 查询语句：查找用户及其密码
    const char *sql = "SELECT password, type FROM users WHERE user = ?;";

    sqlite3_stmt *stmt;

    // 编译 SQL 语句
    rc = sqlite3_prepare_v2(db, sql, -1, &stmt, 0);
    if (rc != SQLITE_OK) {
        strcpy(errmsg,"Error:database error.");
        *recall=-1;
        sqlite3_close(db);
        return;
    }

    // 绑定查询参数
    sqlite3_bind_text(stmt, 1, username, -1, SQLITE_STATIC);

    rc = sqlite3_step(stmt);
    if (rc == SQLITE_ROW) {
        // 查找到用户，获取密码
        const char *db_password = (const char *)sqlite3_column_text(stmt, 0);

        // 如果密码匹配
        if (db_password && strcmp(db_password, password) == 0) {
            const char *db_type = (const char *)sqlite3_column_text(stmt, 1);
            strcpy(Username,username);
            *recall = db_type[0]-'0';
        } else {
            strcpy(errmsg,"Incorrect username or password.");
            *recall=-1;
        }
    } else {
        strcpy(errmsg,"Incorrect username or password.");
        *recall=-1;
    }
    // 绑定查询参数
    // 清理资源
    sqlite3_finalize(stmt);
    sqlite3_close(db);

    return;
}

void Signin(const char *username,const char*password,int *recall,char *errmsg){
    if(!username[0]){
        strcpy(errmsg,"The username is empty!");
        *recall=-1;
        return;
    }
    if(!password[0]){
        strcpy(errmsg,"The password is empty!");
        *recall=-1;
        return;
    }
    sqlite3 *db;
    char *errMsg = 0;
    int rc;
    // 打开数据库，如果数据库文件不存在则创建它
    rc = sqlite3_open("./data/msg.db", &db);
    if (rc) {
        strcpy(errmsg,"Error:database error.");
        *recall=-1;
        return;
    }
    const char *sql = "SELECT user FROM users WHERE user = ?;";

    sqlite3_stmt *stmt;

    // 编译 SQL 语句
    rc = sqlite3_prepare_v2(db, sql, -1, &stmt, 0);
    if (rc != SQLITE_OK) {
        strcpy(errmsg,"Error:database error.");
        *recall=-1;
        sqlite3_close(db);
        return;
    }

    // 绑定查询参数
    sqlite3_bind_text(stmt, 1, username, -1, SQLITE_STATIC);

    rc = sqlite3_step(stmt);
    if (rc == SQLITE_ROW) {
        // 查找到用户
        strcpy(errmsg,"Username has been used.");
        *recall=-1;
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        return;
    }
    else sqlite3_finalize(stmt);
    char *sql_insert="INSERT INTO users (user,password,type) VALUES (?, ? ,'4');";
    sqlite3_stmt *insert;
    rc = sqlite3_prepare_v2(db, sql_insert, -1, &insert, 0);
    if (rc != SQLITE_OK) {
        strcpy(errmsg,"Error:database error.");
        *recall=-1;
        sqlite3_close(db);
        return;
    }

    // 将第一个参数 (username) 绑定到 SQL 语句中的第一个 "?"
    sqlite3_bind_text(insert, 1, username, -1, SQLITE_STATIC);

    // 将第二个参数 (password) 绑定到 SQL 语句中的第二个 "?"
    sqlite3_bind_text(insert, 2, password, -1, SQLITE_STATIC);

    rc = sqlite3_step(insert);
    if (rc != SQLITE_DONE) {
        strcpy(errmsg,"Error:database error");
        sqlite3_free(errMsg);
        sqlite3_finalize(insert);
        sqlite3_close(db);
        *recall=-1;return;
    }
    sqlite3_free(errMsg);
    sqlite3_finalize(insert);
    sqlite3_close(db);
    *recall=0;
    return;
}

void db_create(int *recall,char *errmsg){
    sqlite3 *db;
    char *errMsg = 0;
    int rc;
    // 打开数据库，如果数据库文件不存在则创建它
    rc = sqlite3_open("./data/msg.db", &db);
    if (rc) {
        strcpy(errmsg,"database error.");
        *recall=-1;
        return;
    }


    const char *sql_create_table =
            "CREATE TABLE IF NOT EXISTS users "
            "("
            "ID INTEGER PRIMARY KEY AUTOINCREMENT,"
            "user TEXT UNIQUE,"
            "password TEXT,"
            "type TEXT"
            ");";

    // 执行 SQL 语句
    rc = sqlite3_exec(db, sql_create_table, 0, 0, &errMsg);
    if (rc != SQLITE_OK) {
        strcpy(errmsg,"Error:database error.");
        sqlite3_free(errMsg);
        sqlite3_close(db);
        *recall=-1;return;
    }


    sql_create_table="CREATE TABLE IF NOT EXISTS tests "
                     "("
                     "ID INTEGER PRIMARY KEY   AUTOINCREMENT,"
                     "test_name TEXT,"
                     "Creater TEXT,"
                     "class TEXT,"
                     "problems_count INTEGER"
                     ");";
    rc = sqlite3_exec(db, sql_create_table, 0, 0, &errMsg);
    if (rc != SQLITE_OK) {
        strcpy(errmsg,"Error:database error.");
        sqlite3_free(errMsg);
        sqlite3_close(db);
        *recall=-1;return;
    }


    sql_create_table="CREATE TABLE IF NOT EXISTS timu "
                     "("
                     "ID INTEGER PRIMARY KEY   AUTOINCREMENT,"
                     "text TEXT UNIQUE,"
                     "answer INTEGER"
                     ");";
    rc = sqlite3_exec(db, sql_create_table, 0, 0, &errMsg);
    if (rc != SQLITE_OK) {
        strcpy(errmsg,"Error:database error.");
        sqlite3_free(errMsg);
        sqlite3_close(db);
        *recall=-1;return;
    }


    sql_create_table="CREATE TABLE IF NOT EXISTS stu"
                     "("
                     "ID INTEGER PRIMARY KEY   AUTOINCREMENT,"
                     "majority TEXT,"
                     "class TEXT,"
                     "name TEXT,"
                     "test_index INTEGER,"
                     "test_name TEXT,"
                     "user TEXT,"
                     "score INTEGER"
                     ");";
    rc = sqlite3_exec(db, sql_create_table, 0, 0, &errMsg);
    if (rc != SQLITE_OK) {
        strcpy(errmsg,"Error:database error.");
        sqlite3_free(errMsg);
        sqlite3_close(db);
        *recall=-1;return;
    }


    sql_create_table="CREATE TABLE IF NOT EXISTS students "
                     "("
                     "ID INTEGER PRIMARY KEY   AUTOINCREMENT,"
                     "user TEXT UNIQUE,"
                     "name TEXT,"
                     "class TEXT,"
                     "majority TEXT"
                     ");";
    rc = sqlite3_exec(db, sql_create_table, 0, 0, &errMsg);
    if (rc != SQLITE_OK) {
        strcpy(errmsg,"Error:database error.");
        sqlite3_free(errMsg);
        sqlite3_close(db);
        *recall=-1;return;
    }

    sql_create_table="CREATE TABLE IF NOT EXISTS class "
                     "("
                     "ID INTEGER PRIMARY KEY   AUTOINCREMENT,"
                     "name TEXT"
                     ");";
    rc = sqlite3_exec(db, sql_create_table, 0, 0, &errMsg);
    if (rc != SQLITE_OK) {
        strcpy(errmsg,"Error:database error.");
        sqlite3_free(errMsg);
        sqlite3_close(db);
        *recall=-1;return;
    }


    sql_create_table="CREATE TABLE IF NOT EXISTS majority "
                     "("
                     "ID INTEGER PRIMARY KEY   AUTOINCREMENT,"
                     "name TEXT"
                     ");";
    rc = sqlite3_exec(db, sql_create_table, 0, 0, &errMsg);
    if (rc != SQLITE_OK) {
        strcpy(errmsg,"Error:database error.");
        sqlite3_free(errMsg);
        sqlite3_close(db);
        *recall=-1;return;
    }
    sql_create_table="CREATE TABLE IF NOT EXISTS test_include "
                     "("
                     "ID INTEGER PRIMARY KEY AUTOINCREMENT,"
                     "text TEXT ,"
                     "answer INTEGER,"
                     "test_index INTEGER"
                     ");";
    rc = sqlite3_exec(db, sql_create_table, 0, 0, &errMsg);
    if (rc != SQLITE_OK) {
        strcpy(errmsg,"Error:database error.");
        sqlite3_free(errMsg);
        sqlite3_close(db);
        *recall=-1;return;
    }
    sqlite3_free(errMsg);
    sqlite3_close(db);
}

int stu_type_check(){
    sqlite3 *db;
    char *errMsg = 0;
    int rc;
    // 打开数据库，如果数据库文件不存在则创建它
    rc = sqlite3_open("./data/msg.db", &db);
    if (rc) {
        sqlite3_close(db);
        return -1;
    }
    const char *sql = "SELECT class FROM students WHERE user = ?;";

    sqlite3_stmt *stmt;

    // 编译 SQL 语句
    rc = sqlite3_prepare_v2(db, sql, -1, &stmt, 0);
    if (rc != SQLITE_OK) {
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        return -1;
    }

    // 绑定查询参数
    sqlite3_bind_text(stmt, 1, Username, -1, SQLITE_STATIC);

    rc = sqlite3_step(stmt);

    if(rc==SQLITE_ROW){
        char *cl=(const char *)sqlite3_column_text(stmt, 0);
        strcpy(class,cl);
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        return 1;
    }
    else{
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        return 0;
    }
}

void stu_type_insert(char *name,char *class,char *majority,int *recall,char *errmsg) {
    if(!name[0]){
        strcpy(errmsg,"The name is empty!");
        *recall=-1;
        return;
    }
    if(!class[0]){
        strcpy(errmsg,"The class is empty!");
        *recall=-1;
        return;
    }
    if(!majority[0]){
        strcpy(errmsg,"The majority is empty!");
        *recall=-1;
        return;
    }

    sqlite3 *db;
    char *errMsg = 0;
    int rc;
    // 打开数据库，如果数据库文件不存在则创建它
    rc = sqlite3_open("./data/msg.db", &db);
    if (rc) {
        strcpy(errmsg,"Error:database error.");
        *recall=-1;
        return;
    }
    const char *sql = "SELECT name FROM class WHERE name = ?;";

    sqlite3_stmt *stmt;

    // 编译 SQL 语句
    rc = sqlite3_prepare_v2(db, sql, -1, &stmt, 0);
    if (rc != SQLITE_OK) {
        strcpy(errmsg,"Error:database error.");
        *recall=-1;
        sqlite3_free(errMsg);
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        return;
    }

    // 绑定查询参数
    sqlite3_bind_text(stmt, 1, class, -1, SQLITE_STATIC);

    rc = sqlite3_step(stmt);

    if(rc!=SQLITE_ROW){
        strcpy(errmsg,"Unaccepted class.");
        sqlite3_free(errMsg);
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        *recall=-1;
        return;
    }
    sql = "SELECT name FROM majority WHERE name = ?;";

    // 编译 SQL 语句
    rc = sqlite3_prepare_v2(db, sql, -1, &stmt, 0);
    if (rc != SQLITE_OK) {
        strcpy(errmsg,"Error:database error.");
        *recall=-1;
        sqlite3_free(errMsg);
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        return;
    }

    // 绑定查询参数
    sqlite3_bind_text(stmt, 1, majority, -1, SQLITE_STATIC);

    rc = sqlite3_step(stmt);

    if(rc!=SQLITE_ROW){
        strcpy(errmsg,"Unaccepted majority.");
        sqlite3_free(errMsg);
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        *recall=-1;
        return;
    }

    sql="INSERT INTO students (user,name,class,majority) VALUES(?,?,?,?)";
    rc = sqlite3_prepare_v2(db, sql, -1, &stmt, 0);
    if (rc != SQLITE_OK) {
        strcpy(errmsg,"Error:database error.");
        *recall=-1;
        sqlite3_free(errMsg);
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        return;
    }
    sqlite3_bind_text(stmt, 1, Username, -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 2, name, -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 3, class, -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 4, majority, -1, SQLITE_STATIC);
    rc = sqlite3_step(stmt);
    if (rc != SQLITE_DONE) {
        strcpy(errmsg,"Error:database error");
        sqlite3_free(errMsg);
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        *recall=-1;return;
    }
    sqlite3_free(errMsg);
    sqlite3_finalize(stmt);
    sqlite3_close(db);
    *recall=0;
    return;
}

void add(char* test,int *recall,char* errmsg){
    if(!test[0]){
        *recall=1;
        return;
    }
    double ans;
    char *test2[9999];
    strcpy(test2,test);
    calculate(test2,recall,errmsg,&ans);
    if(*recall==-1)return;
    sqlite3 *db;
    char *errMsg = 0;
    int rc;
    // 打开数据库，如果数据库文件不存在则创建它
    rc = sqlite3_open("./data/msg.db", &db);
    if (rc) {
        strcpy(errmsg,"Error:database error.");
        *recall=-1;
        return;
    }
    char *sql_insert="INSERT INTO timu (text,answer) VALUES (?, ?);";
    sqlite3_stmt *insert;
    rc = sqlite3_prepare_v2(db, sql_insert, -1, &insert, 0);
    if (rc != SQLITE_OK) {
        strcpy(errmsg,"Error:database error.");
        *recall=-1;
        sqlite3_close(db);
        return;
    }

    // 将第一个参数 (username) 绑定到 SQL 语句中的第一个 "?"
    sqlite3_bind_text(insert, 1, test, -1, SQLITE_STATIC);

    // 将第二个参数 (password) 绑定到 SQL 语句中的第二个 "?"
    sqlite3_bind_double(insert, 2, ans);

    rc = sqlite3_step(insert);
    if (rc != SQLITE_DONE) {
        strcpy(errmsg,"Error:database error");
        sqlite3_free(errMsg);
        sqlite3_finalize(insert);
        sqlite3_close(db);
        *recall=-1;return;
    }
    sqlite3_free(errMsg);
    sqlite3_finalize(insert);
    sqlite3_close(db);
    *recall=0;
    return;
}