# Path: july/people/models.py
# class Project(models.Model):
#     """
#     Project Model:
# 
#     This is either a brand new project or an already existing project
#     such as #django, #fabric, #tornado, #pip, etc.
# 
#     When a user Tweets a url we can automatically create anew project
#     for any of the repo host we know already. (github, bitbucket)
#     """
# 
#     url = models.CharField(max_length=255)
#     description = models.TextField(blank=True)
#     name = models.CharField(max_length=255, blank=True)
#     forked = models.BooleanField(default=False)
#     forks = models.IntegerField(default=0)
#     watchers = models.IntegerField(default=0)
#     parent_url = models.CharField(max_length=255, blank=True)
#     created_on = models.DateTimeField(auto_now_add=True)
#     updated_on = models.DateTimeField(auto_now=True)
#     slug = models.SlugField()
#     service = models.CharField(max_length=30, blank=True, default='')
#     repo_id = models.IntegerField(blank=True, null=True)
#     active = models.BooleanField(default=True)
# 
#     def __unicode__(self):
#         if self.name:
#             return self.name
#         else:
#             return self.slug
# 
#     def save(self, *args, **kwargs):
#         self.slug = self.project_name
#         super(Project, self).save(*args, **kwargs)
# 
#     @property
#     def points(self):
#         try:
#             board = self.board_set.latest()
#         except:
#             return 0
#         return board.points
# 
#     @property
#     def total(self):
#         return self.points
# 
#     @property
#     def project_name(self):
#         return self.parse_project_name(self.url)
# 
#     def get_absolute_url(self):
#         return reverse('project-details', args=[self.slug])
# 
#     @classmethod
#     def create(cls, **kwargs):
#         """Get or create shortcut."""
#         repo_id = kwargs.get('repo_id')
#         url = kwargs.get('url')
#         slug = cls.parse_project_name(url)
#         service = kwargs.get('service')
# 
#         # If the repo is on a service with no repo id, we can't handle renames.
#         if not repo_id:
#             project, created = cls.objects.get_or_create(
#                 slug=slug, defaults=kwargs)
# 
#         # Catch renaming of the repo.
#         else:
#             defaults = kwargs.copy()
#             defaults['slug'] = slug
#             project, created = cls.objects.get_or_create(
#                 service=service, repo_id=repo_id,
#                 defaults=defaults)
#             if created and cls.objects.filter(slug=slug).count() > 1:
#                 # This is an old project that was created without a repo_id.
#                 project.delete()  # Delete the duplicate project
#                 project = cls.objects.get(slug=slug)
# 
#         if not project.active:
#             # Don't bother updating this project and don't add commits.
#             return None
# 
#         # Update stale project information.
#         project.update(slug, created, **kwargs)
#         return project
# 
#     @classmethod
#     def _get_bitbucket_data(cls, **kwargs):
#         """Update info from bitbucket if needed."""
#         url = kwargs.get('url', '')
#         parsed = urlparse(url)
#         if parsed.netloc == 'bitbucket.org':
#             # grab data from the bitbucket api
#             # TODO: (rmyers) authenticate with oauth?
#             api = 'https://bitbucket.org/api/1.0/repositories%s'
#             try:
#                 r = requests.get(api % parsed.path)
#                 data = r.json()
#                 kwargs['description'] = data.get('description') or ''
#                 kwargs['forks'] = data.get('forks_count') or 0
#                 kwargs['watchers'] = data.get('followers_count') or 0
#             except:
#                 logging.exception("Unable to parse: %s", url)
#         return kwargs.iteritems()
# 
#     def update(self, slug, created, **kwargs):
#         old = (now() - self.updated_on).seconds >= 21600
#         if created or old or slug != self.slug:
#             for key, value in self._get_bitbucket_data(**kwargs):
#                 setattr(self, key, value)
#             self.slug = slug
#             self.save()
# 
#     @classmethod
#     def parse_project_name(cls, url):
#         """
#         Parse a project url and return a name for it.
# 
#         Example::
# 
#             Given:
#               http://github.com/julython/julython.org
#             Return:
#               gh-julython-julython.org
# 
#         This is used as the Key name in order to speed lookups during
#         api requests.
#         """
#         if not url:
#             return
#         hosts_lookup = {
#             'github.com': 'gh',
#             'bitbucket.org': 'bb',
#         }
#         parsed = urlparse(url)
#         path = parsed.path
#         if path.startswith('/'):
#             path = path[1:]
#         tokens = path.split('/')
#         netloc_slug = parsed.netloc.replace('.', '-')
#         host_abbr = hosts_lookup.get(parsed.netloc, netloc_slug)
#         name = '-'.join(tokens)
#         if name.endswith('-'):
#             name = name[:-1]
#         name = name.replace('.', '_')
#         return '%s-%s' % (host_abbr, name)


import json
import logging
from django.core.management.base import BaseCommand, CommandError
from july.people.models import Project




class Command(BaseCommand):
    args = '<project.json>'
    help = 'Load projects from json file'

    def handle(self, *args, **options):
        if len(args) != 1:
            raise CommandError('Must supply a JSON file of projects.')

        with open(args[0], 'r') as project_file:
            projects = json.loads(project_file.read())
            for project in projects['models']:
                try:

# Path: july/people/models.py
# class Project(models.Model):
#     """
#     Project Model:
# 
#     This is either a brand new project or an already existing project
#     such as #django, #fabric, #tornado, #pip, etc.
# 
#     When a user Tweets a url we can automatically create anew project
#     for any of the repo host we know already. (github, bitbucket)
#     """
# 
#     url = models.CharField(max_length=255)
#     description = models.TextField(blank=True)
#     name = models.CharField(max_length=255, blank=True)
#     forked = models.BooleanField(default=False)
#     forks = models.IntegerField(default=0)
#     watchers = models.IntegerField(default=0)
#     parent_url = models.CharField(max_length=255, blank=True)
#     created_on = models.DateTimeField(auto_now_add=True)
#     updated_on = models.DateTimeField(auto_now=True)
#     slug = models.SlugField()
#     service = models.CharField(max_length=30, blank=True, default='')
#     repo_id = models.IntegerField(blank=True, null=True)
#     active = models.BooleanField(default=True)
# 
#     def __unicode__(self):
#         if self.name:
#             return self.name
#         else:
#             return self.slug
# 
#     def save(self, *args, **kwargs):
#         self.slug = self.project_name
#         super(Project, self).save(*args, **kwargs)
# 
#     @property
#     def points(self):
#         try:
#             board = self.board_set.latest()
#         except:
#             return 0
#         return board.points
# 
#     @property
#     def total(self):
#         return self.points
# 
#     @property
#     def project_name(self):
#         return self.parse_project_name(self.url)
# 
#     def get_absolute_url(self):
#         return reverse('project-details', args=[self.slug])
# 
#     @classmethod
#     def create(cls, **kwargs):
#         """Get or create shortcut."""
#         repo_id = kwargs.get('repo_id')
#         url = kwargs.get('url')
#         slug = cls.parse_project_name(url)
#         service = kwargs.get('service')
# 
#         # If the repo is on a service with no repo id, we can't handle renames.
#         if not repo_id:
#             project, created = cls.objects.get_or_create(
#                 slug=slug, defaults=kwargs)
# 
#         # Catch renaming of the repo.
#         else:
#             defaults = kwargs.copy()
#             defaults['slug'] = slug
#             project, created = cls.objects.get_or_create(
#                 service=service, repo_id=repo_id,
#                 defaults=defaults)
#             if created and cls.objects.filter(slug=slug).count() > 1:
#                 # This is an old project that was created without a repo_id.
#                 project.delete()  # Delete the duplicate project
#                 project = cls.objects.get(slug=slug)
# 
#         if not project.active:
#             # Don't bother updating this project and don't add commits.
#             return None
# 
#         # Update stale project information.
#         project.update(slug, created, **kwargs)
#         return project
# 
#     @classmethod
#     def _get_bitbucket_data(cls, **kwargs):
#         """Update info from bitbucket if needed."""
#         url = kwargs.get('url', '')
#         parsed = urlparse(url)
#         if parsed.netloc == 'bitbucket.org':
#             # grab data from the bitbucket api
#             # TODO: (rmyers) authenticate with oauth?
#             api = 'https://bitbucket.org/api/1.0/repositories%s'
#             try:
#                 r = requests.get(api % parsed.path)
#                 data = r.json()
#                 kwargs['description'] = data.get('description') or ''
#                 kwargs['forks'] = data.get('forks_count') or 0
#                 kwargs['watchers'] = data.get('followers_count') or 0
#             except:
#                 logging.exception("Unable to parse: %s", url)
#         return kwargs.iteritems()
# 
#     def update(self, slug, created, **kwargs):
#         old = (now() - self.updated_on).seconds >= 21600
#         if created or old or slug != self.slug:
#             for key, value in self._get_bitbucket_data(**kwargs):
#                 setattr(self, key, value)
#             self.slug = slug
#             self.save()
# 
#     @classmethod
#     def parse_project_name(cls, url):
#         """
#         Parse a project url and return a name for it.
# 
#         Example::
# 
#             Given:
#               http://github.com/julython/julython.org
#             Return:
#               gh-julython-julython.org
# 
#         This is used as the Key name in order to speed lookups during
#         api requests.
#         """
#         if not url:
#             return
#         hosts_lookup = {
#             'github.com': 'gh',
#             'bitbucket.org': 'bb',
#         }
#         parsed = urlparse(url)
#         path = parsed.path
#         if path.startswith('/'):
#             path = path[1:]
#         tokens = path.split('/')
#         netloc_slug = parsed.netloc.replace('.', '-')
#         host_abbr = hosts_lookup.get(parsed.netloc, netloc_slug)
#         name = '-'.join(tokens)
#         if name.endswith('-'):
#             name = name[:-1]
#         name = name.replace('.', '_')
#         return '%s-%s' % (host_abbr, name)


# Path: july/management/commands/load_projects.py
import json
import logging
from django.core.management.base import BaseCommand, CommandError
from july.people.models import Project





class Command(BaseCommand):
    args = '<project.json>'
    help = 'Load projects from json file'

    def handle(self, *args, **options):
        if len(args) != 1:
            raise CommandError('Must supply a JSON file of projects.')

        with open(args[0], 'r') as project_file:
            projects = json.loads(project_file.read())
            for project in projects['models']:
                try:

                    Project.objects.get_or_create(