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

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:test_sa/controllers/api_routes/api_manager.dart';
import 'package:test_sa/controllers/api_routes/urls.dart';
import 'package:test_sa/extensions/string_extensions.dart';

import 'questionnaire_model.dart';

class SurveyProvider with ChangeNotifier {
  bool loading = false;

  void reset() {
    loading = false;
    // questionnaire = null;
    // ChatApiClient().chatLoginResponse = null;
  }

  getQuestionnaire(int surveySubmissionId, Function(String message, Questionnaire? questionnaire) onResponse) async {
    String responseMsg = "";
    Questionnaire? q;
    try {
      final response = await ApiManager.instance.get("${URLs.getQuestionnaire}?surveySubmissionId=$surveySubmissionId", enableToastMessage: false);
      if (response.statusCode >= 200 && response.statusCode < 300) {
        q = Questionnaire.fromJson(jsonDecode(response.body)["data"]);
      } else {
        if (jsonDecode(response.body)["message"] != null && jsonDecode(response.body)["message"].toString().isNotEmpty) {
          responseMsg = jsonDecode(response.body)["message"];
        } else {}
      }
    } catch (ex) {
      "Failed, Retry.".showToast;
    }
    onResponse(responseMsg, q);

    // return null;
  }

  Future<bool> submitQuestionare(Map<String, dynamic> payload) async {
    try {
      final response = await ApiManager.instance.post(URLs.submitSurvey, body: payload);
      if (response.statusCode >= 200 && response.statusCode < 300) {
        return true;
      }
    } catch (ex) {
      "Failed, Retry.".showToast;
    }
    return false;
  }
}
