# Path: hub/falkor/models.py
# class Project(models.Model):
#     editor_type = models.ForeignKey(EditorType)
#     name = models.CharField(max_length=200)
#     slug = AutoSlugField(populate_from=lambda x: x.user.username+'-'+x.name, null=True, blank=True, always_update=True, editable=True)
#     user = models.ForeignKey(User, related_name='created_projects')
#     container_id = models.CharField(max_length=200, null=True, blank=True)
#     
#     created_at = models.DateTimeField(auto_now_add=True)
#     modified_at = models.DateTimeField(auto_now=True)
#     
#     class Meta:
#         unique_together = (("name", "user"),)
#         permissions = (
#             ("can_open_ide", "Can open IDE"),
#             ("can_start_stop", "Can control the container"),
#             ("can_edit_shares", "Can edit shares"),
#         )
#     
#     def __unicode__(self):
#         from utilities import docker_cli
#         cli = docker_cli()
#         try:
#             container = cli.inspect_container(self.container_id)
#             return u'Project {1}/{0}   [{2}] - {3}'.format(self.name, self.user, self.slug, str(container['NetworkSettings']['Networks'].keys()))
#         except:
#             return u'Project {1}/{0}   [{2}] - {3}'.format(self.name, self.user, self.slug, 'Missing')
#      
#     @property   
#     def urlPrefix(self):
#         return self.editor_type.urlPrefix.format(**vars(self))
#     
#     @property
#     def urlSuffix(self):
#         return self.editor_type.urlSuffix.format(**vars(self))
# 
# class EditorType(models.Model):
#     name = models.CharField(max_length=200, unique=True)
#     slug = AutoSlugField(populate_from='name')
#     image = models.CharField(max_length=200)
#     urlPrefix = models.CharField(max_length=200, blank=True)
#     urlSuffix = models.CharField(max_length=200, blank=True)
#     settings = models.TextField(null=True, blank=True)
#     
#     def __unicode__(self):
#         from utilities import docker_cli
#         cli = docker_cli()
#         try:
#             img = cli.inspect_image(self.image)
#             image = img['Id'] + ' ' + str(img['RepoTags'])
#         except Exception as e:
#             print e
#             image = 'Missing'
#         return '{} [image: {}]'.format(self.name, image)
# 
# Path: hub/falkor/utilities.py
# def docker_cli():
#     return Client(version=settings.DOCKER_API, base_url='http://docker:2375')
# 
# def get_or_create_user_network(cli, user):
#     network_name = 'falkor__user_{0}__'.format(user.pk)
#     
#     networks = cli.networks(names=[network_name])
#     if len(networks) < 1:
#         network = cli.create_network(network_name, 'bridge')
#         network['Name'] = network_name
#     else:
#         network = networks[0]
#         
#     return network


from django.contrib import admin
from .models import Project, EditorType
from django.contrib.auth.models import User
from guardian.admin import GuardedModelAdmin
from .utilities import docker_cli, get_or_create_user_network
            from guardian.shortcuts import assign_perm
            assign_perm('change_project', workspace.user, workspace)
            
            user_network = get_or_create_user_network(cli, workspace.user)
            print user_network
            container = cli.inspect_container(workspace.container_id)
            if container['State']['Status'] == 'running':
                for name, network in container["NetworkSettings"]["Networks"].items():
                    if user_network['Name'] != name and name != 'bridge':
                        cli.disconnect_container_from_network(container['Id'], name)
                if user_network['Name'] not in container["NetworkSettings"]["Networks"]:
                    cli.connect_container_to_network(container['Id'], user_network['Name'])
                for proxy in cli.containers(filters={'status':'running', 'label': ['com.docker.compose.service=proxy']}):
                    if user_network['Name'] not in proxy["NetworkSettings"]["Networks"]:
                        cli.connect_container_to_network(proxy['Id'], user_network['Name'])
            workspace.save()
    
    def claim_workspaces(self, request, queryset):   
        cli = docker_cli()
        for container in cli.containers(filters={'ancestor': 'kdelfour/cloud9-docker'}):
            if container['Names'][0].startswith('/falkor__user_'):
                if Project.objects.filter(container_id=container['Id']).count() == 0:
                    workspace = Project()
                    workspace.user = User.objects.get(username='sueastside')
                    workspace.name = container['Names'][0].split('__workspace_', 1)[1]
                    while Project.objects.filter(name__iexact=workspace.name, user=workspace.user).count():
                        workspace.name = workspace.name + '_'
                    workspace.container_id = container['Id']
                    workspace.save()
    claim_workspaces.short_description = "Claim workspaces"        


# Path: hub/falkor/models.py
# class Project(models.Model):
#     editor_type = models.ForeignKey(EditorType)
#     name = models.CharField(max_length=200)
#     slug = AutoSlugField(populate_from=lambda x: x.user.username+'-'+x.name, null=True, blank=True, always_update=True, editable=True)
#     user = models.ForeignKey(User, related_name='created_projects')
#     container_id = models.CharField(max_length=200, null=True, blank=True)
#     
#     created_at = models.DateTimeField(auto_now_add=True)
#     modified_at = models.DateTimeField(auto_now=True)
#     
#     class Meta:
#         unique_together = (("name", "user"),)
#         permissions = (
#             ("can_open_ide", "Can open IDE"),
#             ("can_start_stop", "Can control the container"),
#             ("can_edit_shares", "Can edit shares"),
#         )
#     
#     def __unicode__(self):
#         from utilities import docker_cli
#         cli = docker_cli()
#         try:
#             container = cli.inspect_container(self.container_id)
#             return u'Project {1}/{0}   [{2}] - {3}'.format(self.name, self.user, self.slug, str(container['NetworkSettings']['Networks'].keys()))
#         except:
#             return u'Project {1}/{0}   [{2}] - {3}'.format(self.name, self.user, self.slug, 'Missing')
#      
#     @property   
#     def urlPrefix(self):
#         return self.editor_type.urlPrefix.format(**vars(self))
#     
#     @property
#     def urlSuffix(self):
#         return self.editor_type.urlSuffix.format(**vars(self))
# 
# class EditorType(models.Model):
#     name = models.CharField(max_length=200, unique=True)
#     slug = AutoSlugField(populate_from='name')
#     image = models.CharField(max_length=200)
#     urlPrefix = models.CharField(max_length=200, blank=True)
#     urlSuffix = models.CharField(max_length=200, blank=True)
#     settings = models.TextField(null=True, blank=True)
#     
#     def __unicode__(self):
#         from utilities import docker_cli
#         cli = docker_cli()
#         try:
#             img = cli.inspect_image(self.image)
#             image = img['Id'] + ' ' + str(img['RepoTags'])
#         except Exception as e:
#             print e
#             image = 'Missing'
#         return '{} [image: {}]'.format(self.name, image)
# 
# Path: hub/falkor/utilities.py
# def docker_cli():
#     return Client(version=settings.DOCKER_API, base_url='http://docker:2375')
# 
# def get_or_create_user_network(cli, user):
#     network_name = 'falkor__user_{0}__'.format(user.pk)
#     
#     networks = cli.networks(names=[network_name])
#     if len(networks) < 1:
#         network = cli.create_network(network_name, 'bridge')
#         network['Name'] = network_name
#     else:
#         network = networks[0]
#         
#     return network


# Path: hub/falkor/admin.py
from django.contrib import admin
from .models import Project, EditorType
from django.contrib.auth.models import User
from guardian.admin import GuardedModelAdmin
from .utilities import docker_cli, get_or_create_user_network
            from guardian.shortcuts import assign_perm

            assign_perm('change_project', workspace.user, workspace)
            
            user_network = get_or_create_user_network(cli, workspace.user)
            print user_network
            container = cli.inspect_container(workspace.container_id)
            if container['State']['Status'] == 'running':
                for name, network in container["NetworkSettings"]["Networks"].items():
                    if user_network['Name'] != name and name != 'bridge':
                        cli.disconnect_container_from_network(container['Id'], name)
                if user_network['Name'] not in container["NetworkSettings"]["Networks"]:
                    cli.connect_container_to_network(container['Id'], user_network['Name'])
                for proxy in cli.containers(filters={'status':'running', 'label': ['com.docker.compose.service=proxy']}):
                    if user_network['Name'] not in proxy["NetworkSettings"]["Networks"]:
                        cli.connect_container_to_network(proxy['Id'], user_network['Name'])
            workspace.save()
    
    def claim_workspaces(self, request, queryset):   
        cli = docker_cli()
        for container in cli.containers(filters={'ancestor': 'kdelfour/cloud9-docker'}):
            if container['Names'][0].startswith('/falkor__user_'):
                if Project.objects.filter(container_id=container['Id']).count() == 0:
                    workspace = Project()
                    workspace.user = User.objects.get(username='sueastside')
                    workspace.name = container['Names'][0].split('__workspace_', 1)[1]
                    while Project.objects.filter(name__iexact=workspace.name, user=workspace.user).count():
                        workspace.name = workspace.name + '_'
                    workspace.container_id = container['Id']
                    workspace.save()
    claim_workspaces.short_description = "Claim workspaces"        


admin.site.register(Project, WorkspaceAdmin)