import 'dart:io';
import 'package:echo_app/global/global.dart';
import 'package:echo_app/services/localization.service.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../models/constant-storage.dart';
import '../models/operator.dart';
import 'package:echo_app/shared/core.session.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';

class LoginService {
  String _url = "";
  Map<String, String>? _httpOptions;
  LoginService() {
    this._httpOptions = {'Content-Type': 'application/json'};
    this._url = CoreSession.api + "API/EchoLogin/";
  }

  main() async {
    var client = http.Client();
    try {
      // ignore: unused_local_variable
      var uriResponse = await client.post(
          Uri.parse(CoreSession.api + "API/EchoLogin/Test"),
          body: {'par': 'doodle'});
    } finally {
      client.close();
    }
  }

  getLanguageId() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    CoreSession.selectedLanguageId =
        prefs.getInt(ConstantStorage.languageId) != null
            ? prefs.getInt(ConstantStorage.languageId)!
            : CoreSession.languages.first.languageId;

    LocalizationService().changeLocale(CoreSession.selectedLanguageId);
  }

  onChangeLanguageBeforeLogin(int languageId) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    CoreSession.selectedLanguageId = languageId;
    prefs.setInt(ConstantStorage.languageId, CoreSession.selectedLanguageId);

    LocalizationService().changeLocale(CoreSession.selectedLanguageId);
  }

  onChangeLanguageAfterLogin(BuildContext context, int languageId) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    CoreSession.selectedLanguageId = languageId;

    prefs.setInt(ConstantStorage.languageId, CoreSession.selectedLanguageId);
    Global.httpOptions = {
      HttpHeaders.authorizationHeader: Global.token,
      HttpHeaders.contentTypeHeader: 'application/json',
      "LanguageId": CoreSession.selectedLanguageId.toString(),
    };

    var userName = prefs.getString(ConstantStorage.username);
    var password = prefs.getString(ConstantStorage.password);
    var organizationId = prefs.getInt(ConstantStorage.organizationId);

    await CoreSession.login(userName, password, organizationId);
    LocalizationService().changeLocale(CoreSession.selectedLanguageId);
  }

  // onChangeLanguageBeforeLogin() async {
  //   SharedPreferences prefs = await SharedPreferences.getInstance();
  //   if (this.languageId == 1) {
  //     this.languageId = 2;
  //     CoreSession.selectedLanguageId = 2;
  //   } else {
  //     this.languageId = 1;
  //     CoreSession.selectedLanguageId = 1;
  //   }
  //   prefs.setInt(ConstantStorage.languageId, this.languageId);
  //   LocalizationService().changeLocale(this.languageId);
  // }

  Future<dynamic> login(userName, password, organizationId, appVersion) async {
    final String urlValue = this._url +
        "Login" +
        "?languageId=" +
        CoreSession.selectedLanguageId.toString();
    var body = jsonEncode({
      'appVersion': appVersion,
      'username': userName,
      'password': password,
      'organizationId': organizationId,
      'fromFlutter': true
    });
    try {
      final response = await http.post(
        Uri.parse(urlValue),
        headers: this._httpOptions,
        body: body,
      );
      return json.decode(response.body);
    } catch (error) {
      print(error);
    }
  }

  Future<dynamic> test() async {
    OperatorForLogin operatorModel = new OperatorForLogin();
    operatorModel.appVersion = 'ver';
    operatorModel.username = 'reema';
    operatorModel.password = 'pass';
    final String urlValue = this._url + "Test" + "?languageId=" + "1";

    Map<String, String> headers = {'Content-Type': 'application/json'};
    var body = jsonEncode({
      'appVersion': operatorModel.appVersion,
      'username': operatorModel.username,
      'password': operatorModel.password,
    });

    return await http
        .post(
      Uri.parse(urlValue),
      headers: headers,
      body: body,
    )
        .then((http.Response response) {
      final int statusCode = response.statusCode;
      // ignore: unnecessary_null_comparison
      if (statusCode < 200 || statusCode > 400 || json == null) {
        throw new Exception("Error while fetching data");
      }
      // return _decoder.convert(response.body);
    });
  }
}
