import 'package:intl/intl.dart';

import 'package:flutter/material.dart';

import 'package:jovial_svg/jovial_svg.dart';

import 'package:country_flags/country_flags.dart';


String _locale2Flag(Locale l) {
  if (l.languageCode == 'en') {
    return 'gb';
  }
  if (l.languageCode == 'uk') {
    return 'ua';
  }
  if (l.languageCode == 'el') {
    return 'gr';
  }
  return l.languageCode;
}

final Map<String, String> localeNames = {
  'ca': 'Català',
  'en': 'English',
  'es': 'Español',
  'fr': 'Français',
  'de': 'Deutsch',
  'uk': 'Українська',
  'el': 'Ελληνικά',
  'ru': 'Русский',
  'pt': 'Português',
  'pl': 'Polski',
  'it': 'Italiano',
  'nl': 'Nederlands',
};

class _CatalanFlag extends StatelessWidget {
  final double? width;
  final double? height;
  final BoxFit? fit;

  _CatalanFlag({
    required this.width, 
    required this.height, 
    required this.fit, 
  });

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: width,
      height: height,
      child: ScalableImageWidget.fromSISource(
        key: const Key('svgFlagCa'),
        si: ScalableImageSource.fromSI(
          DefaultAssetBundle.of(context),
          'packages/pshared/assets/flag_of_catalonia.si',
        ),
        fit: BoxFit.contain,
      ),
    );
  }
} 

Widget getCountryFlag(Locale locale, {double? height = 24, double? width = 35}) {
  return locale.languageCode.toLowerCase() == 'ca' 
    ? _CatalanFlag(width: width, height: height, fit: BoxFit.contain)
    : CountryFlag.fromCountryCode(
        _locale2Flag(locale),
        theme: ImageTheme(
          height: height,
          width: width,
          shape: Rectangle(),
        ),
      );
}

String getLocaleName(Locale locale) {
  return localeNames[locale.languageCode] ?? Intl.canonicalizedLocale(locale.toString()).toUpperCase();
}

Widget getLocaleNameWidget(Locale locale) {
  return Text(getLocaleName(locale), overflow: TextOverflow.ellipsis);
}

Widget getFlaggedLocale(Locale locale) {
  return ListTile(
    leading: getCountryFlag(locale),
    title: getLocaleNameWidget(locale),
  );
}

