import 'package:hooks_riverpod/hooks_riverpod.dart';

import '../../../common/domain/metal_type.dart';
import '../data/market_models.dart';
import '../data/mock_market_repository.dart';

final marketControllerProvider =
    StateNotifierProvider<MarketController, MarketState>((ref) {
      final repository = ref.watch(mockMarketRepositoryProvider);
      return MarketController(repository);
    });

class MarketState {
  const MarketState({
    required this.selectedMetal,
    required this.period,
    required this.quote,
    required this.points,
    required this.quotes,
  });

  final MetalType selectedMetal;
  final MarketPeriod period;
  final MetalQuote quote;
  final List<MarketPoint> points;
  final List<MetalQuote> quotes;

  MarketState copyWith({
    MetalType? selectedMetal,
    MarketPeriod? period,
    MetalQuote? quote,
    List<MarketPoint>? points,
    List<MetalQuote>? quotes,
  }) {
    return MarketState(
      selectedMetal: selectedMetal ?? this.selectedMetal,
      period: period ?? this.period,
      quote: quote ?? this.quote,
      points: points ?? this.points,
      quotes: quotes ?? this.quotes,
    );
  }
}

class MarketController extends StateNotifier<MarketState> {
  MarketController(this._repository)
    : super(
        MarketState(
          selectedMetal: MetalType.gold,
          period: MarketPeriod.h24,
          quote: _repository.quoteFor(MetalType.gold),
          points: _repository.chartFor(MetalType.gold, MarketPeriod.h24),
          quotes: _repository.getQuotes(),
        ),
      );

  final MockMarketRepository _repository;

  void selectMetal(MetalType metal) {
    state = state.copyWith(
      selectedMetal: metal,
      quote: _repository.quoteFor(metal),
      points: _repository.chartFor(metal, state.period),
    );
  }

  void selectPeriod(MarketPeriod period) {
    state = state.copyWith(
      period: period,
      points: _repository.chartFor(state.selectedMetal, period),
    );
  }
}
