// 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/widgets.dart';
import 'package:wyatt_i18n/wyatt_i18n.dart';

/// {@template locale_parser}
/// A parser that parses a [String] into a [Locale].
/// Example:
/// ```dart
/// final parser = LocaleParser();
/// final locale = parser.parse('en-US');
/// // locale.languageCode == 'en'
/// // locale.countryCode == 'US'
/// ```
/// {@endtemplate}
class LocaleParser extends Parser<String, Locale> {
  /// {@macro locale_parser}
  const LocaleParser() : super();

  @override
  Locale parse(String input) {
    final languageParts = RegExp('([a-z]*)[_-]?([a-z|A-Z]*)').firstMatch(input);
    final languageCode = languageParts?.group(1);
    final countryCode = languageParts?.group(2);
    if (languageCode == null) {
      throw ParserException("Can't parse locale tag '$input'", null);
    }

    return Locale(languageCode, countryCode);
  }

  /// Serializes the given [locale] into a [String].
  String serialize(Locale locale) => locale.countryCode == null
      ? locale.languageCode
      : '${locale.languageCode}_${locale.countryCode}';
}
