import 'package:vital_local_database/index.dart';
import 'package:vitalapp/database/db_patch/add_usercode.dart';
import 'package:vitalapp/database/entities/diagnosis.dart';
import 'package:vitalapp/database/entities/patient.dart';
import 'repositories/interfaces/diagnosis.dart';
import 'repositories/interfaces/patient.dart';
import 'repositories/diagnosis.dart';
import 'repositories/patient.dart';
import 'package:fis_common/logger/logger.dart';

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

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

  @override
  IDatabase get database => _database;

  @override
  VitalDatabaseRepositoryStore get repositories => _store;

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

  ///检查本地数据库版本，以判断是否需要升级
  Future<void> checkAndUpgradeDatabaseVersion() async {
    var originalVersion = await _database.getVersion();
    logger.w(
        "VitalDatabaseAccessor checkAndUpgradeDatabaseVersion originalVersion:$originalVersion.");
    if (originalVersion == 0) {
      await db.database.execute(PatientEntity.TABLE_CREATE_SQL);
      await db.database.execute(DiagnosisEntity.TABLE_CREATE_SQL);
    }

    var databasepatch = DatabasePatchAddUserCode(); //新增userCode
    var version = await databasepatch.performTask(originalVersion);

    if (version != originalVersion) {
      await _connection.close();
      _database = await _connection.open();
    }
    logger.w(
        "VitalDatabaseAccessor checkAndUpgradeDatabaseVersion version:$version.");
  }

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

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

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