import 'dart:async';
import 'dart:convert';

import 'package:test_sa/controllers/api_routes/urls.dart';
import 'package:test_sa/models/user.dart';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../settings/app_settings.dart';


class SettingProvider extends ChangeNotifier{

  resetSettings() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    user = null;
    prefs.remove(ASettings.user);
    notifyListeners();
  }

  // check if setting loaded or not
  bool isLoaded = false;

  // contain saved user data
  User user;

  Future<void> setUser(User user) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString(ASettings.user, json.encode(user.toJson()));
    this.user = user;
    notifyListeners();
  }

  String _host;
  String get host => _host;
  Future<void> setHost(String host) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString(ASettings.host, host);
    _host = host;
    notifyListeners();
  }

  String _language;
  String get language => _language;
  Future<void> setLanguage(String currentLanguage) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString(ASettings.language, currentLanguage);
    _language = currentLanguage;
    notifyListeners();
  }

  String _speechToText;
  String get speechToText => _speechToText;
  Future<void> setSpeechToText(String currentLanguage) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString(ASettings.speechToText, currentLanguage);
    _speechToText = currentLanguage;
    notifyListeners();
  }

  // call loadSharedPreferences when provider initialise
  SettingProvider(){
    loadSharedPreferences();
  }

  // get app setting
  Future<void> loadSharedPreferences() async {

    SharedPreferences prefs = await SharedPreferences.getInstance();

    if(prefs.containsKey(ASettings.language)){
      _language = prefs.getString(ASettings.language);
    }else{
      _language  = 'en';
    }

    if(prefs.containsKey(ASettings.speechToText)){
      _speechToText = prefs.getString(ASettings.speechToText);
    }else{
      _speechToText  = 'ar';
    }

    if(prefs.containsKey(ASettings.user)){
      String userJson = prefs.getString(ASettings.user);
      user = User.fromJson(json.decode(userJson));
    }

    if(prefs.containsKey(ASettings.host)){
      _host = prefs.getString(ASettings.host);
    } else{
      _host = URLs.host1;
    }

    isLoaded = true;
    notifyListeners();
  }

}