import 'package:ride/constant/table_names.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

class DbSql {
  static final DbSql instance = DbSql._();

  static Database? _database;

  DbSql._();

  Future<Database> get database async {
    if (_database != null) return _database!;
    _database = await _initDatabase();
    return _database!;
  }

  Future<Database> _initDatabase() async {
    String path = join(await getDatabasesPath(), 'my_database.db');
    return await openDatabase(
      path,
      version: 1,
      onCreate: (db, version) async {
        await db.execute('''
          CREATE TABLE IF NOT EXISTS  ${TableName.carLocations}(
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            driver_id TEXT,
            latitude REAL,
            longitude REAL,
            created_at TEXT,
            updated_at TEXT
          )
        ''');
        await db.execute('''
          CREATE TABLE IF NOT EXISTS ${TableName.placesFavorite}(
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            latitude REAL,
            longitude REAL,
            name TEXT UNIQUE,
            rate TEXT
          )
        ''');
        await db.execute('''
          CREATE TABLE IF NOT EXISTS ${TableName.driverOrdersRefuse}(
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            order_id TEXT,
            created_at TEXT,
            driver_id TEXT
          )
        ''');
      },
    );
  }

  Future<List<Map<String, dynamic>>> getAllData(String table) async {
    Database db = await instance.database;
    return await db.query(table);
  }

  Future<List<Map<String, dynamic>>> getCustomQuery(String query) async {
    Database db = await instance.database;
    return await db.rawQuery(query);
  }

  Future<int> insertData(Map<String, dynamic> map, String table) async {
    Database db = await instance.database;
    return await db.insert(table, map);
  }

  Future<int> updateData(Map<String, dynamic> map, String table, int id) async {
    Database db = await instance.database;

    return await db.update(table, map, where: 'id = ?', whereArgs: [id]);
  }

  Future<int> deleteData(String table, int id) async {
    Database db = await instance.database;
    return await db.delete(table, where: 'id = ?', whereArgs: [id]);
  }

  Future<int> deleteAllData(String table) async {
    Database db = await instance.database;
    return await db.delete(table);
  }
}
