// Copyright (C) 2023 WYATT GROUP
// Please see the AUTHORS file for details.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

import 'package:flutter/cupertino.dart';
import 'package:wyatt_i18n/wyatt_i18n.dart';

/// {@template i18n_delegate}
/// A [LocalizationsDelegate] that loads the [I18n] instance from
/// the [I18nDataSource].
/// {@endtemplate}
class I18nDelegate extends LocalizationsDelegate<I18n> {
  /// {@macro i18n_delegate}
  I18nDelegate({
    required this.dataSource,
  });

  final I18nDataSource dataSource;

  /// The current locale.
  Locale? currentLocale;

  /// Since we are using the [I18nDataSource] to load the i18n file,
  /// we don't need to check if the locale is supported.
  /// We can just return `true`.
  @override
  bool isSupported(Locale locale) => true;

  @override
  Future<I18n> load(Locale locale) async {
    currentLocale = locale;
    final i18n = await dataSource.load(locale: locale);

    return i18n;
  }

  @override
  bool shouldReload(I18nDelegate old) =>
      currentLocale != null || currentLocale != old.currentLocale;
}
