// Copyright 2022, the Flutter project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:puzzleweave/persistence/persistence.dart';

/// An class that holds settings like [playerName] or [musicOn],
/// and saves them to an injected persistence store.
class SettingsController {
  final Persistence _persistence;

  /// Whether or not the sound is on at all. This overrides both music
  /// and sound.
  ValueNotifier<bool> sound = ValueNotifier(true);
  ValueNotifier<bool> music = ValueNotifier(true);
  ValueNotifier<bool> vibrate = ValueNotifier(true);
  ValueNotifier<int> skin = ValueNotifier(0);

  /// Creates a new instance of [SettingsController] backed by [persistence].
  SettingsController({required Persistence persistence}) : _persistence = persistence;

  /// Asynchronously loads values from the injected persistence store.
  Future<void> loadStateFromPersistence() async {
    sound.value = _persistence.sound;
    music.value = _persistence.music;
    vibrate.value = _persistence.vibrate;
    skin.value = _persistence.skin;
  }

  void toggleSound() {
    sound.value = !sound.value;
    _persistence.sound = sound.value;
  }

  void toggleMusic() {
    music.value = !music.value;
    _persistence.music = music.value;
  }

  void toggleVibrate() {
    vibrate.value = !vibrate.value;
    _persistence.vibrate = vibrate.value;
  }

  void setSkin(int value) {
    skin.value = value;
    _persistence.skin = value;
  }
}
