try:
    from django.forms.utils import ValidationError
except ImportError:
    from django.forms.util import ValidationError

from django_facebook import settings as facebook_settings, signals
from django_facebook.exceptions import FacebookException
from django_facebook.utils import get_user_model, mass_get_or_create, \
    cleanup_oauth_url, get_profile_model, parse_signed_request, hash_key, \
    try_get_profile, get_user_attribute
from open_facebook import exceptions as open_facebook_exceptions
from open_facebook.exceptions import OpenFacebookException
from open_facebook.utils import send_warning, validate_is_instance
import datetime
import json
import logging
try:
    from dateutil.parser import parse as parse_date
except ImportError:
    from django_facebook.utils import parse_like_datetime as parse_date


logger = logging.getLogger(__name__)


def require_persistent_graph(request, *args, **kwargs):
    '''
    Just like get_persistent graph, but instead of returning None
    raise an OpenFacebookException if we can't access facebook
    '''
    kwargs['raise_'] = True
    graph = get_persistent_graph(request, *args, **kwargs)
    if not graph:
        raise OpenFacebookException('please authenticate')
    return graph


def require_facebook_graph(request, *args, **kwargs):
    '''
    Just like get_facebook graph, but instead of returning None
    raise an OpenFacebookException if we can't access facebook
    '''
    kwargs['raise_'] = True
    graph = get_facebook_graph(request, *args, **kwargs)
    if not graph:
        raise OpenFacebookException('please authenticate')
    return graph


def get_persistent_graph(request, *args, **kwargs):
    '''
    Wraps itself around get facebook graph
    But stores the graph in the session, allowing usage across multiple
    pageviews.
    Note that Facebook session's expire at some point, you can't store this
    for permanent usage
    Atleast not without asking for the offline_access permission
    '''
    from open_facebook.api import OpenFacebook
    if not request:
        raise(ValidationError,
              'Request is required if you want to use persistent tokens')

    graph = None
    # some situations like an expired access token require us to refresh our
    # graph
    require_refresh = False
    code = request.REQUEST.get('code')
    if code:
        require_refresh = True

    local_graph = getattr(request, 'facebook', None)
    if local_graph:
        # gets the graph from the local memory if available
        graph = local_graph

    if not graph:
        # search for the graph in the session
        cached_graph_dict = request.session.get('graph_dict')
        if cached_graph_dict:
            graph = OpenFacebook()
            graph.__setstate__(cached_graph_dict)
            graph._me = None

    if not graph or require_refresh:
        # gets the new graph, note this might do token conversions (slow)
        graph = get_facebook_graph(request, *args, **kwargs)
        # if it's valid replace the old cache
        if graph is not None and graph.access_token:
            request.session['graph_dict'] = graph.__getstate__()

    # add the current user id and cache the graph at the request level
    _add_current_user_id(graph, request.user)
    request.facebook = graph

    return graph


def get_facebook_graph(request=None, access_token=None, redirect_uri=None, raise_=False):
    '''
    given a request from one of these
    - js authentication flow (signed cookie)
    - facebook app authentication flow (signed cookie)
    - facebook oauth redirect (code param in url)
    - mobile authentication flow (direct access_token)
    - offline access token stored in user profile

    returns a graph object

    redirect path is the path from which you requested the token
    for some reason facebook needs exactly this uri when converting the code
    to a token
    falls back to the current page without code in the request params
    specify redirect_uri if you are not posting and recieving the code
    on the same page
    '''
    # this is not a production flow, but very handy for testing
    if not access_token and request.REQUEST.get('access_token'):
        access_token = request.REQUEST['access_token']
    # should drop query params be included in the open facebook api,
    # maybe, weird this...
    from open_facebook import OpenFacebook, FacebookAuthorization
    from django.core.cache import cache
    expires = None
    if hasattr(request, 'facebook') and request.facebook:
        graph = request.facebook
        _add_current_user_id(graph, request.user)
        return graph

    # parse the signed request if we have it
    signed_data = None
    if request:
        signed_request_string = request.REQUEST.get('signed_data')
        if signed_request_string:
            logger.info('Got signed data from facebook')
            signed_data = parse_signed_request(signed_request_string)
        if signed_data:
            logger.info('We were able to parse the signed data')

    # the easy case, we have an access token in the signed data
    if signed_data and 'oauth_token' in signed_data:
        access_token = signed_data['oauth_token']

    if not access_token:
        # easy case, code is in the get
        code = request.REQUEST.get('code')
        if code:
            logger.info('Got code from the request data')

        if not code:
            # signed request or cookie leading, base 64 decoding needed
            cookie_name = 'fbsr_%s' % facebook_settings.FACEBOOK_APP_ID
            cookie_data = request.COOKIES.get(cookie_name)

            if cookie_data:
                signed_request_string = cookie_data
                if signed_request_string:
                    logger.info('Got signed data from cookie')
                signed_data = parse_signed_request(signed_request_string)
                if signed_data:
                    logger.info('Parsed the cookie data')
                # the javascript api assumes a redirect uri of ''
                redirect_uri = ''

            if signed_data:
                # parsed data can fail because of signing issues
                if 'oauth_token' in signed_data:
                    logger.info('Got access_token from parsed data')
                    # we already have an active access token in the data
                    access_token = signed_data['oauth_token']
                else:
                    logger.info('Got code from parsed data')
                    # no access token, need to use this code to get one
                    code = signed_data.get('code', None)

        if not access_token:
            if code:
                cache_key = hash_key('convert_code_%s' % code)
                access_token = cache.get(cache_key)
                if not access_token:
                    # exchange the code for an access token
                    # based on the php api
                    # https://github.com/facebook/php-sdk/blob/master/src/base_facebook.php
                    # create a default for the redirect_uri
                    # when using the javascript sdk the default
                    # should be '' an empty string
                    # for other pages it should be the url
                    if not redirect_uri:
                        redirect_uri = ''

                    # we need to drop signed_data, code and state
                    redirect_uri = cleanup_oauth_url(redirect_uri)

                    try:
                        logger.info(
                            'trying to convert the code with redirect uri: %s',
                            redirect_uri)
                        # This is realy slow, that's why it's cached
                        token_response = FacebookAuthorization.convert_code(
                            code, redirect_uri=redirect_uri)