import 'package:path/path.dart';
import 'package:skillcourt/pages/play_setup/play_setup_item.dart';
import 'package:sqflite/sqflite.dart';

class DBHelper {
  static Database? _database;
  static const String TABLE_SAVEGAME = "saved_games";

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

  Future<Database?> initDatabase() async {
    final String path = await getDatabasesPath();
    final String databasePath =
        join(path, 'saved_games.db'); // Provide your database file name

    try {
      final db = await openDatabase(
        databasePath,
        version: 1,
        onCreate: _onCreate,
      );

      return db;
    } catch (e) {
      print('Error opening database: $e');
      return null;
    }
  }

  Future _onCreate(Database db, int version) async {
    await db.execute(
      'CREATE TABLE $TABLE_SAVEGAME'
      '(session_name TEXT NOT NULL,'
      'id INTEGER PRIMARY KEY,'
      'pad_light_up INTEGER,'
      'pad_light_delay INTEGER,'
      'game_repeats TEXT,'
      'minutes INTEGER,'
      'seconds INTEGER,'
      'num_of_hits INTEGER,'
      'game_length TEXT,'
      'pad_sequence TEXT' //TODO modify type to fit app requirements
      ')',
    );
  }

  Future addPlaySetUp(PlaySetUpItem playSetUp) async {
    var dbClient = await db;
    await dbClient.insert(TABLE_SAVEGAME, playSetUp.toMap());
    print(dbClient.path);
    // return playSetUp;
  }

  Future<int> deletePlaySetUp(int id) async {
    var dbClient = await db;
    return await dbClient
        .delete(TABLE_SAVEGAME, where: 'id = ?', whereArgs: [id]);
  }

  Future<List<PlaySetUpItem>> getAllPlaySetUps() async {
    var dbClient = await db;
    final List<Map<String, Object?>> results =
        await dbClient.query(TABLE_SAVEGAME);

    List<PlaySetUpItem> playSetups = results.map((result) {
      return PlaySetUpItem(
        result['id'] as int,
        padLightUp: result['pad_light_up'] as int,
        padLightDelay: result['pad_light_delay'] as int,
        gameRepeats: result['game_repeats'] as String,
        padSequence: result['pad_sequence'] as String, //TODO Modify type
        // You may need to adjust the type
        minutes: result['minutes'] as int?,
        seconds: result['seconds'] as int?,
        numOfHits: result['num_of_hits'] as int?,
        name: result['session_name'] as String?,
        gameLength: result['game_length']
            as String?, // Assuming "session_name" exists in your database
      );
    }).toList();

    return playSetups;
  }

  Future<int> getCountPlaySetUps() async {
    var dbClient = await db;
    final result = await dbClient
        .rawQuery('SELECT COUNT(*) as count FROM $TABLE_SAVEGAME');
    if (result.isNotEmpty) {
      return Sqflite.firstIntValue(result) ?? 0;
    } else {
      return 0;
    }
  }

  Future close() async {
    final dbClient = await db;
    dbClient.close();
  }
}
