import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

const kDefaultLanguage = 'tk';

class SettingsModel extends ChangeNotifier {
  String _language = kDefaultLanguage;

  static AppLocalizations? _localization;
  static Future<void> initLocalization(String l) async {
    _localization =
        await AppLocalizations.delegate.load(Locale(l, l == 'en' ? 'US' : ''));
    await AppLocalizations.delegate.load(Locale(l));
  }

  Future<void> setLanguage(String l) async {
    _language = l;
    await initLocalization(l);
    var prefs = await SharedPreferences.getInstance();
    await prefs.setString('language', _language);
    notifyListeners();
  }

  String get currentLanguage => _language;

  Locale get language {
    switch (_language) {
      case 'ru':
        return const Locale('ru', '');
      case 'en':
        return const Locale('en', 'US');
      case 'tk':
        return const Locale('tk', '');
      default:
        return const Locale('tk', '');
    }
  }

  void launch(SharedPreferences prefs) {
    _language = prefs.getString('language') ?? _language;
    notifyListeners();
  }

  SettingsModel(SharedPreferences prefs) {
    launch(prefs);
  }

  static SettingsModel of(BuildContext context, [bool listen = false]) {
    return Provider.of<SettingsModel>(context, listen: listen);
  }
}

extension LocalMessageExt on String {
  String get translation {
    return <String, String?>{
          "categories": SettingsModel._localization?.categories,
          "searchHint": SettingsModel._localization?.searchHint,
          "email": SettingsModel._localization?.email,
          "enter_your_email": SettingsModel._localization?.enter_your_email,
          "password": SettingsModel._localization?.password,
          "enter_your_password":
              SettingsModel._localization?.enter_your_password,
          "enter_your_password_here":
              SettingsModel._localization?.enter_your_password_here,
          "login": SettingsModel._localization?.login,
          "or": SettingsModel._localization?.or,
          "register": SettingsModel._localization?.register,
          "your_phone_number": SettingsModel._localization?.your_phone_number,
          "repeat_password": SettingsModel._localization?.repeat_password,
          "repeat_password_to_confirm":
              SettingsModel._localization?.repeat_password_to_confirm,
        }[this] ??
        this;
  }
}
