import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import '../model/student.dart';

class DatabaseHelper {
  static final DatabaseHelper instance = DatabaseHelper._instance();
  static Database? _database;

  DatabaseHelper._instance();

  Future<Database> get db async {
    _database ??= await initDb();
    return _database!;
  }

  Future<Database> initDb() async {
    String databasesPath = await getDatabasesPath();
    String path = join(databasesPath, 'student_university.db');

    return await openDatabase(path, version: 1, onCreate: _onCreate);
  }

  Future _onCreate(Database db, int version) async {
    await db.execute('''
      CREATE TABLE student (
        studentNFCCardId TEXT PRIMARY KEY,
        firstName TEXT,
        name TEXT,
        promotion TEXT,
        studentId TEXT
      )
    ''');
  }

  Future<int> insertUser(Student student) async {
    Database db = await instance.db;
    return await db.insert('student', student.toMap());
  }

  Future<List<Map<String, dynamic>>> queryAllUsers() async {
    Database db = await instance.db;
    return await db.query('student');
  }

  Future<int> updateUser(Student student) async {
    Database db = await instance.db;
    return await db.update('student', student.toMap(), where: 'studentNFCCardId = ?', whereArgs: [student.studentNFCCardId]);
  }

  Future<int> deleteUser(String studentNFCCardId) async {
    Database db = await instance.db;
    return await db.delete('student', where: 'studentNFCCardId = ?', whereArgs: [studentNFCCardId]);
  }
}