# Path: wtfhack/base/models.py
# class Repo(models.Model):
#     # Full name is required
#     full_name = models.CharField(max_length=500, unique=True, null=False)
#     url = models.URLField(null=True)
#     language = models.ForeignKey(Language, related_name='repos')
#     description = models.CharField(max_length=500, null=True, blank=True)
# 
# 
#     def save(self, *args, **kwargs):
#         '''Override save method to set default url.'''
#         BASE = 'https://github.com/'
#         # Default url to base url + full_name
#         if not self.url:
#             self.url = BASE + self.full_name
#         super(Repo, self).save(*args, **kwargs)
# 
# 
#     def __unicode__(self):
#         return "{full_name}: {language}".format(full_name=self.full_name,
#                                                 language=self.language.name)
# 
# class Language(models.Model):
#     name = models.CharField(max_length=40, null=False)
#     learn_url = models.URLField(null=True, blank=True)
# 
#     @staticmethod
#     def all():
#         return [l.name for l in Language.objects.order_by('name')]
#     def __unicode__(self):
#         return self.name


import random
from django.core.urlresolvers import reverse
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.utils import simplejson
from django.views.decorators.csrf import ensure_csrf_cookie
from wtfhack.base.models import Repo, Language
from social_auth.models import UserSocialAuth
from github import Github
@ensure_csrf_cookie     
def submit(request):
    """ View for the submit page.
    """
    if request.user.is_active:
        user = UserSocialAuth.objects.filter(provider='github').get(user_id=request.user.id)
        github = Github(user.tokens[u'access_token'])
        repos = [repo for repo in github.get_user().get_repos()]
        return render(request, 'base/submit.html', {'repos': repos})
    else:
        return HttpResponseRedirect(reverse('socialauth_begin', args=('github',)))

def add_repo(request):
    """ View for adding a repo.
    """
    user = UserSocialAuth.objects.filter(provider='github').get(user_id=request.user.id)
    github = Github(user.tokens[u'access_token'])
    name = request.POST['name']
    repo = github.get_user().get_repo(name)
    message = {'success': None}
    try:
        language_str = repo.language.lower()
    except AttributeError:
        message['success'] = False
        message['message'] = "Could not add repo because it doesn't have a language. Try specifying the language in your Github repo settings."
        json = simplejson.dumps(message)
        return HttpResponse(json, mimetype='application/json')

    # TODO: exception handling here
    language_obj, created_lang = Language.objects.get_or_create(name=language_str)

# Path: wtfhack/base/models.py
# class Repo(models.Model):
#     # Full name is required
#     full_name = models.CharField(max_length=500, unique=True, null=False)
#     url = models.URLField(null=True)
#     language = models.ForeignKey(Language, related_name='repos')
#     description = models.CharField(max_length=500, null=True, blank=True)
# 
# 
#     def save(self, *args, **kwargs):
#         '''Override save method to set default url.'''
#         BASE = 'https://github.com/'
#         # Default url to base url + full_name
#         if not self.url:
#             self.url = BASE + self.full_name
#         super(Repo, self).save(*args, **kwargs)
# 
# 
#     def __unicode__(self):
#         return "{full_name}: {language}".format(full_name=self.full_name,
#                                                 language=self.language.name)
# 
# class Language(models.Model):
#     name = models.CharField(max_length=40, null=False)
#     learn_url = models.URLField(null=True, blank=True)
# 
#     @staticmethod
#     def all():
#         return [l.name for l in Language.objects.order_by('name')]
#     def __unicode__(self):
#         return self.name


# Path: wtfhack/base/views.py
import random
from django.core.urlresolvers import reverse
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.utils import simplejson
from django.views.decorators.csrf import ensure_csrf_cookie
from wtfhack.base.models import Repo, Language
from social_auth.models import UserSocialAuth
from github import Github

@ensure_csrf_cookie     
def submit(request):
    """ View for the submit page.
    """
    if request.user.is_active:
        user = UserSocialAuth.objects.filter(provider='github').get(user_id=request.user.id)
        github = Github(user.tokens[u'access_token'])
        repos = [repo for repo in github.get_user().get_repos()]
        return render(request, 'base/submit.html', {'repos': repos})
    else:
        return HttpResponseRedirect(reverse('socialauth_begin', args=('github',)))

def add_repo(request):
    """ View for adding a repo.
    """
    user = UserSocialAuth.objects.filter(provider='github').get(user_id=request.user.id)
    github = Github(user.tokens[u'access_token'])
    name = request.POST['name']
    repo = github.get_user().get_repo(name)
    message = {'success': None}
    try:
        language_str = repo.language.lower()
    except AttributeError:
        message['success'] = False
        message['message'] = "Could not add repo because it doesn't have a language. Try specifying the language in your Github repo settings."
        json = simplejson.dumps(message)
        return HttpResponse(json, mimetype='application/json')

    # TODO: exception handling here
    language_obj, created_lang = Language.objects.get_or_create(name=language_str)

    repo_obj, created_repo = Repo.objects.get_or_create(full_name=repo.full_name,