# -*- coding: utf-8 -*-
import smtplib
import socket
import ssl
import sys

from celery import exceptions as celery_exceptions
from django.template import exceptions as template_exceptions
from requests import exceptions as requests_exceptions

from events.surveyme_integration.exceptions.base import (
    ConnectionError,
    IntegrationError,
    NetworkError,
    TaskTimeoutError,
    TemplateSyntaxError,
)
from events.surveyme_integration.exceptions.email import (
    EmailConnectionError,
    EmailDataError,
    EmailRecipientError,
    EmailSenderError,
)


def reraise(service_type, cause):
    error_class = get_error_class(service_type, cause)
    if isinstance(error_class, type):
        exception = error_class(cause)
    else:
        exception = error_class
    raise exception.with_traceback(sys.exc_info()[2])


def get_general_error(ex):
    if isinstance(ex, celery_exceptions.SoftTimeLimitExceeded):
        return TaskTimeoutError
    if isinstance(ex, template_exceptions.TemplateSyntaxError):
        return TemplateSyntaxError
    if isinstance(ex, (socket.error, ssl.SSLError)):
        return NetworkError
    if isinstance(ex, requests_exceptions.ConnectionError):
        return ConnectionError
    if isinstance(ex, requests_exceptions.RequestException):
        return NetworkError
    return IntegrationError


def get_email_error(ex):
    if isinstance(ex, smtplib.SMTPServerDisconnected):
        return EmailConnectionError
    if isinstance(ex, smtplib.SMTPRecipientsRefused):
        return EmailRecipientError
    if isinstance(ex, smtplib.SMTPSenderRefused):
        return EmailSenderError
    if isinstance(ex, smtplib.SMTPDataError):
        return EmailDataError


def get_wiki_error(ex):
    pass


def get_post_error(ex):
    pass


def get_startrek_error(ex):
    pass


def get_error_class(service_type, ex):
    error_class = None
    if service_type.slug == 'email':
        error_class = get_email_error(ex)
    elif service_type.slug == 'wiki':
        error_class = get_wiki_error(ex)
    elif service_type.slug == 'startrek':
        error_class = get_startrek_error(ex)
    elif service_type.slug in ('http', 'json_rpc', ):
        error_class = get_post_error(ex)
    if error_class is None:
        error_class = get_general_error(ex)
    return error_class
