import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:http/http.dart';
import 'package:test_sa/controllers/api_routes/urls.dart';
import 'package:test_sa/models/app_notification.dart';
import 'package:test_sa/models/user.dart';

class NotificationsProvider extends ChangeNotifier{

  // number of items call in each request
  final pageItemNumber = 20;

  //reset provider data
  void reset(){
    notifications = null;
    nextPage = true;
    stateCode = null;
  }

  // state code of current request to defied error message
  // like 400 customer request failed
  // 500 service not available
  int stateCode;

  // true if there is next page in product list and false if not
  bool nextPage = true;

  // list of user requests
  List<AppNotification> notifications;

  // when requests in-process _loading = true
  // done _loading = true
  // failed _loading = false
  bool isLoading;


  /// 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> getNotifications ({
    @required String host,
    @required User user,
    @required int hospitalId,
  }) async {
    if(isLoading == true)
      return -2;
    isLoading = true;
    notifyListeners();
    Response response;
   // userId = 397.toString(); // testing id to view data
    try{
      response = await get(
          Uri.parse(URLs.getNotifications
          +"?uid=${user.id}"
          "&token=${user.token}"
          "&page=${(notifications?.length ?? 0) ~/pageItemNumber}"),
        headers: {
            "Content-Type":"application/json; charset=utf-8"
        }
      );
      stateCode = response.statusCode;
      if(response.statusCode >= 200 && response.statusCode < 300) {
        // client's request was successfully received
        List requestsListJson = json.decode(utf8.decode(response.bodyBytes));
        List<AppNotification> _serviceRequestsPage = requestsListJson.map(
                (request) => AppNotification.fromJson(request)).toList();
        if(notifications == null)
          notifications = [];
        notifications.addAll(_serviceRequestsPage);
        if(_serviceRequestsPage.length == pageItemNumber){
          nextPage = true;
        }else{
          nextPage = false;
        }
      }
      isLoading = false;
      notifyListeners();
      return response.statusCode;
    } catch(error) {
      isLoading = false;
      stateCode = -1;
      notifyListeners();
      return -1;
    }

  }

  /// 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<List<AppNotification>> getRecentNotifications ({
    @required String host,
    @required User user,
  }) async {
    Response response;
    //userId = 397.toString(); // testing id to view data

    try{
      response = await get(
          Uri.parse(host+URLs.getNotifications
              +"?uid=${user.id}&token=${user.token}"),
          headers: {
            "Content-Type":"application/json; charset=utf-8"
          }
      );

      stateCode = response.statusCode;
      if(response.statusCode >= 200 && response.statusCode < 300) {
        // client's request was successfully received
        List requestsListJson = json.decode(utf8.decode(response.bodyBytes));
        List<AppNotification> _recentNotifications = requestsListJson.map(
                (request) => AppNotification.fromJson(request)).toList();
        return _recentNotifications;
      }
      return null;

    } catch(error) {
      return null;
    }

  }
}