import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart';
import '../helper/helper.dart';

class ExceptionHandlers {
  getExceptionString(error) {
    if (error is SocketException) {
      return 'No internet connection.';
    } else if (error is HttpException) {
      return 'HTTP error occurred.';
    } else if (error is FormatException) {
      return 'Invalid data format.';
    } else if (error is TimeoutException) {
      return 'Request time out.';
    } else if (error is BadRequestException) {
      return error.message.toString();
    } else if (error is UnAuthorizedException) {
      return error.message.toString();
    } else if (error is NotFoundException) {
      return error.message.toString();
    } else if (error is FetchDataException) {
      return error.message.toString();
    } else {
      return 'Unknown error occurred.';
    }
  }
}


class AppException implements Exception {
  final String? message;
  final String? prefix;
  final String? url;

  AppException([this.message, this.prefix, this.url]);
}

class BadRequestException extends AppException {
  BadRequestException([String? message, String? url])
      : super(message, 'Bad request', url);
}

class FetchDataException extends AppException {
  FetchDataException([String? message, String? url])
      : super(message, 'Unable to process the request', url);
}

class ApiNotRespondingException extends AppException {
  ApiNotRespondingException([String? message, String? url])
      : super(message, 'Api not responding', url);
}

class UnAuthorizedException extends AppException {
  UnAuthorizedException([String? message, String? url])
      : super(message, 'Unauthorized request', url);
}

class NotFoundException extends AppException {
  NotFoundException([String? message, String? url])
      : super(message, 'Data not found', url);
}

dynamic processResponse(Response response) {
  switch (response.statusCode) {
    case 200:
      var responseJson = response.body;
      return jsonDecode(responseJson.toString());
    case 400: //Bad request
      showMessage('Bad request');
      throw BadRequestException(jsonDecode(response.body)['message']);
    case 401: //Unauthorized
      showMessage('Unauthorized');
      throw UnAuthorizedException(jsonDecode(response.body)['message']);
    case 403: //Forbidden
      showMessage('Forbidden');
      throw UnAuthorizedException(jsonDecode(response.body)['message']);
    case 404: //Resource Not Found
      showMessage('Resource Not Found');
      throw NotFoundException(jsonDecode(response.body)['message']);
    case 500: //Internal Server Error
      showMessage('Internal Server Error');
    default:
      showMessage('Something went wrong! ${response.statusCode}');
      throw FetchDataException('');
  }
}