import 'dart:io';

import 'package:flutter/services.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart' as sqflite_ffi;
import 'package:sqflite_common_ffi/sqflite_ffi.dart';

class WorkDatabase {
  static final WorkDatabase instance = WorkDatabase._init();
  
  static Database? _database;
  bool _isInitialized = false;

  WorkDatabase._init() {
    sqflite_ffi.sqfliteFfiInit();
  }

  Future<void> initDatabase() async {
    if (!_isInitialized) {
      _database = await _initDB('work.db');
      await _createDB(_database!, 1);
      _isInitialized = true;
    }
  }

  Future<Database> get database async {
    if (!_isInitialized) {
      await initDatabase();
    }
    return _database!;
  }

  Future<Database> _initDB(String filePath) async {
    final documentsDirectory = await getApplicationDocumentsDirectory();
    final path = join(documentsDirectory.path, filePath);

    bool dbExists = await File(path).exists();
    if (!dbExists) {
      try {
        ByteData data = await rootBundle.load('assets/database/$filePath');
        List<int> bytes =
            data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
        await File(path).writeAsBytes(bytes);
      } catch (e) {
        print("No pre-existing database found in assets, creating new one");
      }
    }

    return await databaseFactoryFfi.openDatabase(path);
  }

  Future<void> _createDB(Database db, int version) async {
    await db.execute('''
      CREATE TABLE IF NOT EXISTS work (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        date TEXT UNIQUE
      )
    ''');
  }

  Future<int> insertDate(String date) async {
    final db = await database;
    try {
      return await db.insert('work', {'date': date});
    } catch (e) {
      // En cas de doublon (date déjà existante)
      return 0;
    }
  }

  Future<List<String>> getDates() async {
    final db = await database;
    final result = await db.query('work');
    return result.map((row) => row['date'] as String).toList();
  }

  Future<List<String>> getDatesDesc() async {
    final db = await database;
    final result = await db.query('work', orderBy: 'date DESC');
    return result.map((row) => row['date'] as String).toList();
  }
}