import 'dart:async';
import 'dart:convert';
import 'dart:developer';

import 'package:mnemo_cards_common/mnemo_cards_common.dart';

import 'package:rxdart/rxdart.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../main.dart';

class PreviewPackHolder {
  final StreamController<PreviewPackState?> _streamController =
      StreamController.broadcast();
  PreviewPackState? _state;

  PreviewPackHolder();

  Future<void> init() async {
    if (_state == null) {
      await loadFromCache();
    }
  }

  Future<void> loadFromCache() async {
    final sp = globalSharedPreferences;
    final previewPacksStrings = sp.getStringList('preview_packs');
    if (previewPacksStrings == null || previewPacksStrings.isEmpty) {
      return;
    }
    final List<CardPackPreviewDto> previewPacks = [];
    previewPacksStrings.forEach((string) {
      try {
        final pack = string.decode(CardPackPreviewDto.fromJson);
        previewPacks.add(pack);
      } catch (e, s) {
        log('Cant load preview pack', error: e, stackTrace: s);
      }
    });
    setPreviewPacks(previewPacks);
  }

  Future<void> savePreviewPacks() async {
    final packs = state?.previewPacks ?? [];
    final stringsList = <String>[];
    packs.forEach((pack) {
      try {
        final string = jsonEncode(pack);
        stringsList.add(string);
      } catch (e, s) {
        log('Cant load preview pack', error: e, stackTrace: s);
      }
    });
    final sp = globalSharedPreferences;
    sp.setStringList('preview_packs', stringsList);
  }

  void setPreviewPacks(List<CardPackPreviewDto> packs, {bool save = false}) {
    _state = PreviewPackState(packs);
    if (save) {
      savePreviewPacks();
    }
    _streamController.add(_state);
  }

  void clear() {
    _state = null;
    _streamController.add(_state);
  }

  PreviewPackState? get state => _state;

  Stream<PreviewPackState?> get asStream =>
      _streamController.stream.startWith(_state);
}

class PreviewPackState {
  final List<CardPackPreviewDto> previewPacks;

  PreviewPackState(this.previewPacks);
}
