import 'package:vital_local_database/index.dart';

import 'entities/patient.dart';
import 'entities/diagnosis.dart';
import 'repositories/interfaces/diagnosis.dart';
import 'repositories/interfaces/patient.dart';
import 'repositories/diagnosis.dart';
import 'repositories/patient.dart';

/// vital 本地数据库对象
final db = VitalDatabaseAccessor();

/// vital本地数据库访问器
class VitalDatabaseAccessor
    extends BaseDbAccessor<VitalDatabaseRepositoryStore> {
  final _store = VitalDatabaseRepositoryStore();
  final _connection = SqliteConnection(path: "vital.db");
  late final IDatabase _database;

  @override
  IDatabase get database => _database;

  @override
  VitalDatabaseRepositoryStore get repositories => _store;

  /// 初始化
  Future<void> init() async {
    _database = await _connection.open();
    await _checkTables();
    _store.regRepository<IPatientRepository>(PatientRepository(database));
    _store.regRepository<IDiagnosisRepository>(DiagnosisRepository(database));
  }

  Future<void> _checkTables() async {
    // await database.execute("DROP TABLE IF EXISTS Patients;");
    await database.execute(PatientEntity.TABLE_CREATE_SQL);
    await database.execute(DiagnosisEntity.TABLE_CREATE_SQL);
  }

  void dispose() {
    _connection.close();
  }
}

class VitalDatabaseRepositoryStore extends BaseDbAccessorRepositoryStore {
  /// 居民仓储
  IPatientRepository get patient => findRepository<IPatientRepository>()!;

  /// 检测记录仓储
  IDiagnosisRepository get diagnosis => findRepository<IDiagnosisRepository>()!;
}
