from django.contrib.auth.models import User
from linkedin.models import LinkedInUser
from connections.models import Connection
from urllib import parse

import requests
import json
import string
import random

def getAuthorizationURL():
    """Gets the auth URL
    used to redirect the user to the LinkedIn oAuth page
    """
    api_key = '75cyxzcm381ngd'
    scope = 'r_fullprofile+r_emailaddress+r_network'
    state = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(20))
    redirect_uri = 'http://localhost:8000/auth'
    return 'https://www.linkedin.com/uas/oauth2/authorization?' + 'response_type=code&client_id=' + api_key + '&scope=' + scope + '&state=' + state + '&redirect_uri=' + redirect_uri

def getAccessTokenURL(code):
    """Gets the access token URL
    used to get the access token
    """
    auth_code = code
    redirect_uri = 'http://localhost:8000/auth'
    api_key = '75cyxzcm381ngd'
    secret_key = 'wpwT0zy4i4BAhWsv'
    return 'https://www.linkedin.com/uas/oauth2/accessToken?grant_type=authorization_code&code=' + auth_code + '&redirect_uri=' + redirect_uri + '&client_id=' + api_key + '&client_secret=' + secret_key
    
def getCode(request):
    """Gets the value of the code param
    Passed through in the URL
    """
    return request.GET['code']

def createUser(token):
    """Creates a user
    Uses the access token passed into this function to get user info
    and store in the db
    """
    basicProfileURL = 'https://api.linkedin.com/v1/people/~?format=json&oauth2_access_token=' + token
    emailURL = 'https://api.linkedin.com/v1/people/~/email-address?format=json&oauth2_access_token=' + token
    person = json.loads(requests.get(basicProfileURL).text)
    email = json.loads(requests.get(emailURL).text)
    username = person['firstName'] + person['lastName']
    try:
        return User.objects.get(username=username)
    except:
        user = User.objects.create_user(username, email, 'password')
        user.first_name = person['firstName']
        user.last_name = person['lastName']
        user.save()
        return user

def storeLinkedinUser(code):
    """Stores and returns LinkedinUser
    Extended user contains the access token generated by Linkedin. Calls the createUser
    function, and then returns the new user object
    """
    res = requests.post(getAccessTokenURL(code))
    token = json.loads(res.text)['access_token']
    user = createUser(token)
    LinkedInUser.addToken(user, token)
    return user

def refreshConnections(user):
    """Refreshes all connections and related data
    """
    token = user.linkedinuser.access_token
    connectionsURL = 'https://api.linkedin.com/v1/people/~/connections:(first-name,last-name,positions:(company),id)?format=json&oauth2_access_token=' + token
    connections = json.loads(requests.get(connectionsURL).text)
    connectionList = connections['values']
    connections = []
    for person in connectionList:
        id = person['id']
        firstName = person['firstName']
        lastName = person['lastName']
        try:
            company = person['positions']['values'][0]['company']['name']
        except:
            company = 'Deadbeat'
        connections.append(Connection.addConnection(id=id, firstName=firstName, lastName=lastName, company=company))
    return connections