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

import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'package:local_auth/local_auth.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:test_sa/controllers/api_routes/api_manager.dart';
import 'package:test_sa/controllers/api_routes/urls.dart';
import 'package:test_sa/models/user.dart';

import '../settings/app_settings.dart';

class SettingProvider extends ChangeNotifier {
  resetSettings() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    user = null;
    _assetGroup = null;
    prefs.remove(ASettings.user);
    prefs.remove(ASettings.localAuth);
    prefs.remove(ASettings.assetGroup);
    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();
    selectAssetGroup(user);
  }

  Future<void> setRememberMe(String username, String password, bool rememberMe) async {
    this.rememberMe = rememberMe;
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setBool(ASettings.rememberMe, rememberMe);
    await prefs.setString(ASettings.userName, username);
    await prefs.setString(ASettings.password, password);
  }

  void selectAssetGroup(User user) {
    if (user.assetGroups.length == 1) {
      _assetGroup = user.assetGroups.first;
    } else {
      int fmIndex = user.assetGroups.indexWhere((element) => element.id == 1);
      if (fmIndex < 0) {
        _assetGroup = user.assetGroups.first;
      } else {
        _assetGroup = user.assetGroups[fmIndex];
      }
    }
    setAssetGroup(_assetGroup);
    // ApiManager.instance.assetGroup = _assetGroup;
  }

  Future<void> setAssetGroup(AssetGroup assetGroup) async {
    // SharedPreferences prefs = await SharedPreferences.getInstance();
    // prefs.setString(ASettings.assetGroup, json.encode(assetGroup.toJson()));
    _assetGroup = assetGroup;
    ApiManager.instance.assetGroup = _assetGroup;
    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;
  AssetGroup _assetGroup;

  String get language => _language;

  AssetGroup get assetGroup => _assetGroup;

  bool rememberMe = false;
  String username = "";
  String password = "";

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

  bool isLocalAuthEnable = false;

  Future<void> setAuth(bool status) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    isLocalAuthEnable = status;
    prefs.setBool(ASettings.localAuth, isLocalAuthEnable);
    notifyListeners();
  }

  String _theme;

  String get theme => _theme;

  bool get localAuth => isLocalAuthEnable;

  Future<void> setDarkTheme(bool value) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    _theme = value ? "dark" : "light";
    prefs.setString(ASettings.theme, _theme);
    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();
  }

  LocalAuthentication auth = LocalAuthentication();

  // 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.theme)) {
      _theme = prefs.getString(ASettings.theme);
    } else {
      _theme = 'light';
    }

    if (prefs.containsKey(ASettings.localAuth)) {
      isLocalAuthEnable = prefs.getBool(ASettings.localAuth);
    } else {
      isLocalAuthEnable = false;
    }

    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));
      selectAssetGroup(user);
    }

    rememberMe = prefs.getBool(ASettings.rememberMe) ?? false;
    username = prefs.getString(ASettings.userName) ?? "";
    password = prefs.getString(ASettings.password) ?? "";

    // if (prefs.containsKey(ASettings.assetGroup)) { //
    //   String assetJson = prefs.getString(ASettings.assetGroup);
    //   _assetGroup = AssetGroup.fromJson(json.decode(assetJson));
    // }

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

    isLoaded = true;
    notifyListeners();
  }

  Future<bool> checkUserTokenValidation(String token) async {
    Response response;
    bool isValid = false;
    try {
      Map<String, dynamic> body = {};
      response = await ApiManager.instance.post(URLs.checkLoginValidation + "?token=$token", body: body);
      if (response.statusCode >= 200 && response.statusCode < 300) {
        isValid = true;
      }

      return isValid;
    } catch (error) {
      return isValid;
    }
  }
}
