import 'dart:io';

import 'package:logging/logging.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';

import '../../globals.dart';
import '../../objectbox.g.dart';

class ObjectBoxCache {
  static final _logger = Logger('ObjectBoxCache');
  static final _openCaches = <String, ObjectBoxCache>{};
  late final Store store;

  ObjectBoxCache._create(this.store);

  static Future<ObjectBoxCache> create({
    String baseDir = 'objectboxcache',
    String? subDir,
  }) async {
    final docsDir = await getApplicationSupportDirectory();

    final path = p.join(docsDir.path, baseDir, subDir);
    _logger.info('ObjectBoxCache path: $path');
    if (_openCaches.containsKey(path)) {
      _logger.fine('Cache already exists for path, returning it: $path');
      return _openCaches[path]!;
    }

    try {
      final directory = Directory(path);
      if (!directory.existsSync()) {
        Directory(path).createSync(recursive: true);
      }
    } catch (e) {
      _logger.severe('Error creating ObjectCachePathDirectory: $e');
    }

    final store = await openStore(
      directory: path,
      macosApplicationGroup: macOsGroupId,
    );
    final cache = ObjectBoxCache._create(store);
    _openCaches[path] = cache;
    _logger.fine('New cache created for path: $path');
    return cache;
  }
}
