import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:http/http.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 '../../../new_views/common_widgets/app_lazy_loading.dart';

class UserProvider extends ChangeNotifier {
  //reset provider data
  void reset() {
    _user = null;
    ApiManager.instance.user = user;
    _loading = false;
  }

  // contain user data
  // when user not login or register _user = null
  User _user;

  User get user => _user;

  File profileImage;

  set user(User user) {
    _user = user;
    ApiManager.instance.user = user;
    notifyListeners();
  }

  // when login or register in-process _login = true
  // when login or register is done or not start = false
  bool _loading = false;

  bool get isLoading => _loading;

  set isLoading(bool isLoading) {
    _loading = isLoading;
    notifyListeners();
  }

  /// sign in with user - need (email or phone) and password;
  /// return -2 if request in progress
  /// return -1 if error happen when sending request
  /// return state code if request complete may be 200, 404 or 403
  /// for more details check http state manager
  /// lib\controllers\http_status_manger\http_status_manger.dart
  Future<int> login({@required BuildContext context, @required User user}) async {
    if (_loading == true) return -2;
    _loading = true;
    notifyListeners();
    Response response;
    try {
      showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
      response = await ApiManager.instance.post(URLs.login, body: await user.toLoginJson());
      _loading = false;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        // client's request was successfully received
        _user = User.fromJson(jsonDecode(response.body));
        _user.profilePhotoName = URLs.getFileUrl(_user.profilePhotoName);
        ApiManager.instance.user = _user;
        notifyListeners();
        Navigator.pop(context);
        return response.statusCode;
      }
      notifyListeners();
      Navigator.pop(context);
      return response.statusCode;
    } catch (error) {
      debugPrint(error);
      Navigator.pop(context);
      _loading = false;
      notifyListeners();
      return -1;
    }
  }

  /// sign up with User object;
  /// return -2 if request in progress
  /// return -1 if error happen when sending request
  /// return state code if request complete may be 200, 404 or 403
  /// for more details about state codes check http state manager
  /// lib\controllers\http_status_manger\http_status_manger.dart
  Future<int> register({
    @required String host,
    @required User user,
  }) async {
    if (_loading == true) return -2;
    _loading = true;
    notifyListeners();
    Response response;
    try {
      response = await ApiManager.instance.post(
        URLs.register,
        body: await user.toLoginJson(),
      );
    } catch (error) {
      _loading = false;
      notifyListeners();
      return -1;
    }
    _loading = false;
    notifyListeners();
    if (response.statusCode >= 200 && response.statusCode < 300) {
      // client's request was successfully received
      _user = User.fromJson(jsonDecode(utf8.decode(response.bodyBytes))[0]);
      _user.clientId = user.clientId;
      _user.clientName = user.clientName;
      notifyListeners();
      return response.statusCode;
    }
    return response.statusCode;
  }

  Future<int> uploadProfileImage(String userId, File image) async {
    if (_loading == true) return -2;
    _loading = true;
    notifyListeners();
    Response response;
    try {
      Map<String, dynamic> body = {
        "userId": userId,
        "imageEmployee": "${image.path.split("/").last}|${base64Encode(image.readAsBytesSync())}",
      };
      response = await ApiManager.instance.post(URLs.updateProfileImage, body: body);
      if (response.statusCode >= 200 && response.statusCode < 300) {
        profileImage = image;
        String imageId = jsonDecode(response.body)["data"];
        _user.profilePhotoName = URLs.getFileUrl(imageId);
        ApiManager.instance.user = _user;
      }
      _loading = false;
      notifyListeners();
      return response.statusCode;
    } catch (error) {
      _loading = false;
      notifyListeners();
      return -1;
    }
  }

// Future<int> updateProfile({
//   @required String host,
//   @required User user,
// }) async {
//   if (_loading == true) return -2;
//   _loading = true;
//   notifyListeners();
//   Response response;
//
//   Map<String, dynamic> jsonObject = {};
//   jsonObject["uid"] = user.id;
//   jsonObject["token"] = user.token;
//   if (user.departmentId != _user.departmentId) jsonObject["department"] = user.departmentId;
//   // if (user.whatsApp != _user.whatsApp) jsonObject["whatsapp"] = user.whatsApp;
//   if (user.phoneNumber != _user.phoneNumber) jsonObject["phone"] = user.phoneNumber;
//   try {
//     response = response = await ApiManager.instance.post(
//       URLs.login,
//       body: jsonObject,
//     );
//   } catch (error) {
//     _loading = false;
//     notifyListeners();
//     return -1;
//   }
//
//   _loading = false;
//   notifyListeners();
//
//   if (response.statusCode >= 200 && response.statusCode < 300) {
//     // client's request was successfully received
//     _user = User.fromJson(jsonDecode(utf8.decode(response.bodyBytes))[0]);
//     _user.clientId = user.clientId;
//     _user.clientName = user.clientName;
//     _user.departmentName = user.departmentName;
//     _user.departmentId = user.departmentId;
//     notifyListeners();
//     return response.statusCode;
//   }
//   return response.statusCode;
// }
}
