# 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))


import socket, struct
from docker import Client
from django.conf import settings
from .models import Project
from guardian.shortcuts import get_objects_for_user
    from guardian.shortcuts import get_perms, get_users_with_perms
    if workspace.container_id:
        try:
            container = cli.inspect_container(workspace.container_id)
            workspace.state['status'] = container['State']['Status']
            workspace.running = container['State']['Status'] == 'running'
            workspace.state['IPAddress'] = container['NetworkSettings']['Networks'].items()[0][1]['IPAddress']
        except Exception as e:
            print e
            pass
    return workspace.state

def get_workspace_endpoints(cli, workspace):
    workspace.endpoints = []
    if workspace.container_id:
        container = cli.inspect_container(workspace.container_id)
        if container['State']['Status'] == 'running':
            command = cli.exec_create(workspace.container_id, 'netstat -tlnp')
            output = cli.exec_start(command['Id'])
            for line in output.split('\n')[2:-1]:
                s = line.split()
                if s[3].startswith('127.0.0.') and s[6] == '-':
                    continue
                if s[3] == '0.0.0.0:80' and s[6].endswith('/node'):
                    continue
                ip = container['NetworkSettings']['Networks'].items()[0][1]['IPAddress'].replace('.', '_')
                name = s[0] +'-'+ ip + '-' +s[3].split(':')[1]
                workspace.endpoints.append({'program': s[6], 'protocol': s[0], 'port': s[3], 'name': name})
    return workspace.endpoints
    
def get_workspaces_for_user(cli, user):

# 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
import socket, struct
from docker import Client
from django.conf import settings
from .models import Project
from guardian.shortcuts import get_objects_for_user
    from guardian.shortcuts import get_perms, get_users_with_perms

    if workspace.container_id:
        try:
            container = cli.inspect_container(workspace.container_id)
            workspace.state['status'] = container['State']['Status']
            workspace.running = container['State']['Status'] == 'running'
            workspace.state['IPAddress'] = container['NetworkSettings']['Networks'].items()[0][1]['IPAddress']
        except Exception as e:
            print e
            pass
    return workspace.state

def get_workspace_endpoints(cli, workspace):
    workspace.endpoints = []
    if workspace.container_id:
        container = cli.inspect_container(workspace.container_id)
        if container['State']['Status'] == 'running':
            command = cli.exec_create(workspace.container_id, 'netstat -tlnp')
            output = cli.exec_start(command['Id'])
            for line in output.split('\n')[2:-1]:
                s = line.split()
                if s[3].startswith('127.0.0.') and s[6] == '-':
                    continue
                if s[3] == '0.0.0.0:80' and s[6].endswith('/node'):
                    continue
                ip = container['NetworkSettings']['Networks'].items()[0][1]['IPAddress'].replace('.', '_')
                name = s[0] +'-'+ ip + '-' +s[3].split(':')[1]
                workspace.endpoints.append({'program': s[6], 'protocol': s[0], 'port': s[3], 'name': name})
    return workspace.endpoints
    
def get_workspaces_for_user(cli, user):

    workspaces = get_objects_for_user(user, 'can_open_ide', klass=Project).order_by('-created_at')