import logging

from allauth.socialaccount.models import SocialToken

from django.conf import settings
from requests_oauthlib import OAuth1Session, OAuth2Session

from .models import GithubProject, GithubOrganization, BitbucketProject, BitbucketTeam
from tastyapi import apiv2

log = logging.getLogger(__name__)


def get_oauth_session(user, provider):

    tokens = SocialToken.objects.filter(account__user__username=user.username, app__provider=provider)
    if tokens.exists():
        token = tokens[0]
    else:
        return None
    if provider == 'github':
        session = OAuth2Session(
            client_id=token.app.client_id,
            token={
                'access_token': str(token.token),
                'token_type': 'bearer'
            }
        )
    elif provider == 'bitbucket':
        session = OAuth1Session(
            token.app.client_id,
            client_secret=token.app.secret,
            resource_owner_key=token.token,
            resource_owner_secret=token.token_secret
        )

    return session or None


def make_github_project(user, org, privacy, repo_json):
    log.info('Trying GitHub: %s' % repo_json['full_name'])
    if (repo_json['private'] is True and privacy == 'private' or
            repo_json['private'] is False and privacy == 'public'):
        project, created = GithubProject.objects.get_or_create(
            full_name=repo_json['full_name'],
            users__pk=user.pk,
        )
        if project.organization and project.organization != org:
            log.debug('Not importing %s because mismatched orgs' % repo_json['name'])
            return None
        else:
            project.organization = org
        project.users.add(user)
        project.name = repo_json['name']
        project.description = repo_json['description']
        project.git_url = repo_json['git_url']
        project.ssh_url = repo_json['ssh_url']
        project.html_url = repo_json['html_url']
        project.json = repo_json
        project.save()
        return project
    else:
        log.debug('Not importing %s because mismatched type' % repo_json['name'])


def make_github_organization(user, org_json):
    org, created = GithubOrganization.objects.get_or_create(
        login=org_json.get('login'),
    )
    org.html_url = org_json.get('html_url')
    org.name = org_json.get('name')
    org.email = org_json.get('email')
    org.json = org_json
    org.users.add(user)