# 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





class WorkspaceAdmin(GuardedModelAdmin):
    actions = ['delete_and_remove', 'fix_networks', 'claim_workspaces']
    
    def get_actions(self, request):
        actions = super(WorkspaceAdmin, self).get_actions(request)
        if 'delete_selected' in actions:
            del actions['delete_selected']
        return actions
        
    def delete_and_remove(self, request, queryset):
        cli = docker_cli()
        for workspace in queryset.all():
            try:
                cli.remove_container(workspace.container_id, force=True)
            except:
                pass
            workspace.delete()
            
    delete_and_remove.short_description = "Delete and remove containers"
    
    def fix_networks(self, request, queryset):

# 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






class WorkspaceAdmin(GuardedModelAdmin):
    actions = ['delete_and_remove', 'fix_networks', 'claim_workspaces']
    
    def get_actions(self, request):
        actions = super(WorkspaceAdmin, self).get_actions(request)
        if 'delete_selected' in actions:
            del actions['delete_selected']
        return actions
        
    def delete_and_remove(self, request, queryset):
        cli = docker_cli()
        for workspace in queryset.all():
            try:
                cli.remove_container(workspace.container_id, force=True)
            except:
                pass
            workspace.delete()
            
    delete_and_remove.short_description = "Delete and remove containers"
    
    def fix_networks(self, request, queryset):

        cli = docker_cli()