from base64 import b64decode
import copy
import importlib

from django.contrib.auth import (get_user_model, authenticate)

from django.core.files.base import ContentFile
from django.core.exceptions import ObjectDoesNotExist
from django.utils.translation import ugettext as _
from rest_framework import serializers

from rest_framework_jwt.compat import (Serializer, get_username_field,
                                       PasswordField)
from rest_framework_jwt.settings import api_settings
from rest_framework.relations import RelatedField
from rest_framework.settings import APISettings

from .oauth2_client import get_local_host
from .models import SocialUserData

User = get_user_model()
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
jwt_get_username_from_payload = api_settings.JWT_PAYLOAD_GET_USERNAME_HANDLER


class ForeignKeyRelatedField(RelatedField):
    """you can customize the field name to filter the result
    """

    def __init__(self, **kwargs):
        self.fname = kwargs.pop('fname', None)
        super().__init__(**kwargs)

    def to_internal_value(self, data):
        try:
            if self.fname:
                filter_kwargs = {self.fname: data}
                return self.get_queryset().get(**filter_kwargs)
            else:
                return self.get_queryset().get(pk=data)

        except ObjectDoesNotExist:
            self.fail('does_not_exist', pk_value=data)
        except (TypeError, ValueError):
            self.fail('incorrect_type', data_type=type(data).__name__)

    def to_representation(self, value):
        if self.fname:
            return getattr(value, self.fname)
        else:
            return value.pk


class JSONWebTokenSerializerWithEmail(Serializer):
    """a customize jwt serializer use email and password.
    """

    def __init__(self, *args, **kwargs):