# Path: hub/falkor/consumers.py
# def create_event(event_name, data):
#     print 'CREATE',  event_name
#     return {
#         "text": json.dumps({
#             "event": event_name,
#             "data": data
#         }, cls=DjangoJSONEncoder)
#     }
# 
# def model_to_dict(instance):
#     w = {field.name: field.value_from_object(instance) for field in instance._meta.fields}
#     w.update({'editor_type': {field.name: field.value_from_object(instance.editor_type) for field in instance.editor_type._meta.fields}})
#     w.update({'user': {'id': instance.user.id, 'username': instance.user.username}})
#     w.update({'shared': getattr(instance, 'shared', None)})
#     w.update({'permissions': getattr(instance, 'permissions', None)})
#     w.update({'shares': getattr(instance, 'shares', None)})
#     w.update({'running': getattr(instance, 'running', None)})
#     w.update({'state': getattr(instance, 'state', None)})
#     w.update({'info': getattr(instance, 'info', None)})
#     w.update({'endpoints': getattr(instance, 'endpoints', None)})
#     w.update({'urlPrefix': getattr(instance, 'urlPrefix', lambda: None)})
#     w.update({'urlSuffix': getattr(instance, 'urlSuffix', lambda: None)})
#     return w
# 
# 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))
# 
# Path: hub/falkor/utilities.py
# def docker_cli():
#     return Client(version=settings.DOCKER_API, base_url='http://docker:2375')
# 
# def get_workspace_full(cli, request_user, workspace):
#     if workspace.container_id:
#         container = cli.inspect_container(workspace.container_id)
#         workspace.info = container
#         get_workspace_state(cli, workspace)
#         get_workspace_endpoints(cli, workspace)
#         
#     workspace.shared = request_user != workspace.user
#     
#     from guardian.shortcuts import get_perms, get_users_with_perms
#     workspace.permissions = dict([(v, True) for v in get_perms(request_user, workspace)])
#     workspace.shares = []
#     for user, perms in get_users_with_perms(workspace, attach_perms=True).items():
#         share = {'username': user.username, 'permissions': dict([(v, True) for v in perms]), 'owner': user == workspace.user}
#         if share['owner']:
#             workspace.shares.insert(0, share)
#         else:
#             workspace.shares.append(share)
#     return workspace


import json
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User
from guardian.shortcuts import assign_perm, remove_perm
from channels import Channel, Group
from channels.auth import channel_session_user
from .consumers import create_event, model_to_dict
from .models import Project
from .utilities import docker_cli, get_workspace_full



@channel_session_user
def shares_edit(message):
    data = json.loads(message['data'])
    workspace = get_object_or_404(Project, pk=data['workspace_id'])
    user = get_object_or_404(User, username=data['username'])
    perms = data.get('permissions', '').split(',')
    
    if not message.user.has_perm('falkor.can_edit_shares', workspace):
        return
    
    if user == workspace.user:
        Group("user-%s" % message.user.pk).send(create_event('notifications', {'level': 'info', 'message': 'you cannot change permissions of the owner'}))
        return
    
    permissions = ['can_open_ide']
    print 'ERR', user, perms
    for perm in permissions:
        if perm in perms:
            print 'Adding', perm, 'for', user
            assign_perm(perm, user, workspace)
        else:
            print 'Removing', perm, 'for', user
            remove_perm(perm, user, workspace)
    
    cli = docker_cli()
    get_workspace_full(cli, message.user, workspace)
    

# Path: hub/falkor/consumers.py
# def create_event(event_name, data):
#     print 'CREATE',  event_name
#     return {
#         "text": json.dumps({
#             "event": event_name,
#             "data": data
#         }, cls=DjangoJSONEncoder)
#     }
# 
# def model_to_dict(instance):
#     w = {field.name: field.value_from_object(instance) for field in instance._meta.fields}
#     w.update({'editor_type': {field.name: field.value_from_object(instance.editor_type) for field in instance.editor_type._meta.fields}})
#     w.update({'user': {'id': instance.user.id, 'username': instance.user.username}})
#     w.update({'shared': getattr(instance, 'shared', None)})
#     w.update({'permissions': getattr(instance, 'permissions', None)})
#     w.update({'shares': getattr(instance, 'shares', None)})
#     w.update({'running': getattr(instance, 'running', None)})
#     w.update({'state': getattr(instance, 'state', None)})
#     w.update({'info': getattr(instance, 'info', None)})
#     w.update({'endpoints': getattr(instance, 'endpoints', None)})
#     w.update({'urlPrefix': getattr(instance, 'urlPrefix', lambda: None)})
#     w.update({'urlSuffix': getattr(instance, 'urlSuffix', lambda: None)})
#     return w
# 
# 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))
# 
# Path: hub/falkor/utilities.py
# def docker_cli():
#     return Client(version=settings.DOCKER_API, base_url='http://docker:2375')
# 
# def get_workspace_full(cli, request_user, workspace):
#     if workspace.container_id:
#         container = cli.inspect_container(workspace.container_id)
#         workspace.info = container
#         get_workspace_state(cli, workspace)
#         get_workspace_endpoints(cli, workspace)
#         
#     workspace.shared = request_user != workspace.user
#     
#     from guardian.shortcuts import get_perms, get_users_with_perms
#     workspace.permissions = dict([(v, True) for v in get_perms(request_user, workspace)])
#     workspace.shares = []
#     for user, perms in get_users_with_perms(workspace, attach_perms=True).items():
#         share = {'username': user.username, 'permissions': dict([(v, True) for v in perms]), 'owner': user == workspace.user}
#         if share['owner']:
#             workspace.shares.insert(0, share)
#         else:
#             workspace.shares.append(share)
#     return workspace


# Path: hub/falkor/workspace_consumers.py
import json
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User
from guardian.shortcuts import assign_perm, remove_perm
from channels import Channel, Group
from channels.auth import channel_session_user
from .consumers import create_event, model_to_dict
from .models import Project
from .utilities import docker_cli, get_workspace_full




@channel_session_user
def shares_edit(message):
    data = json.loads(message['data'])
    workspace = get_object_or_404(Project, pk=data['workspace_id'])
    user = get_object_or_404(User, username=data['username'])
    perms = data.get('permissions', '').split(',')
    
    if not message.user.has_perm('falkor.can_edit_shares', workspace):
        return
    
    if user == workspace.user:
        Group("user-%s" % message.user.pk).send(create_event('notifications', {'level': 'info', 'message': 'you cannot change permissions of the owner'}))
        return
    
    permissions = ['can_open_ide']
    print 'ERR', user, perms
    for perm in permissions:
        if perm in perms:
            print 'Adding', perm, 'for', user
            assign_perm(perm, user, workspace)
        else:
            print 'Removing', perm, 'for', user
            remove_perm(perm, user, workspace)
    
    cli = docker_cli()
    get_workspace_full(cli, message.user, workspace)
    

    Group("user-%s" % message.user.pk).send(create_event('workspaces.select', model_to_dict(workspace)))