# Path: threebot/models.py
# class Worker(models.Model):
#     ACCESS_REQUEST_TIMEOUT = 1
#     STATUS_OFFLINE = 0
#     STATUS_ONLINE = 1
#     STATUS_BUSY = 9
#     STATUS_MUTED = 10
#     STATUS_CHOICES = (
#         (STATUS_OFFLINE, 'offline'),
#         (STATUS_ONLINE, 'online'),
#         (STATUS_BUSY, 'busy'),
#         (STATUS_MUTED, 'muted'),
#     )
# 
#     owner = models.ForeignKey(Organization, help_text="Worker owner")
#     title = models.CharField(max_length=255)
#     slug = models.SlugField(_('slug'), max_length=50, unique=True)
# 
#     date_created = models.DateTimeField(auto_now_add=True)
#     date_modified = models.DateTimeField(auto_now=True)
# 
#     ip = models.GenericIPAddressField("IP-Address",)
#     addr = models.CharField(max_length=200, null=True, blank=True, help_text='For now we use the IP to connect to the worker')
#     port = models.PositiveIntegerField(default=55555)
#     secret_key = models.CharField(max_length=200, null=True, blank=True, help_text='The Secret Key. Never share yours.')
# 
#     muted = models.BooleanField(default=False, help_text="Mute a Worker to prevent accessibility checks and improve performance.")
# 
#     pre_task = models.TextField(null=True, blank=True, help_text='this will run as a Script before the worker performs a workflow')
#     post_task = models.TextField(null=True, blank=True, help_text='this will run as a Script after the worker has performed a workflow')
# 
#     class Meta():
#         ordering = ['owner', 'title']
#         verbose_name = _("Worker")
#         verbose_name_plural = _("Workers")
# 
#     def get_status_display(self):
#         choices = dict(self.STATUS_CHOICES)
#         return choices[self.status]
# 
#     @cached_property
#     def status(self):
#         if self.muted:
#             return self.STATUS_MUTED
#         if self.is_busy:
#             return self.STATUS_BUSY
#         if self.is_accessible:
#             return self.STATUS_ONLINE
#         else:
#             return self.STATUS_OFFLINE
# 
#     @cached_property
#     def is_busy(self):
#         """Identifies is a Worfkflow is currently blocking this worker."""
#         return WorkflowLog.objects.filter(exit_code=WorkflowLog.PENDING, performed_on=self).exists()
# 
#     @cached_property
#     def is_accessible(self):
#         if self.muted:
#             return False
# 
#         try:
#             from .botconnection import BotConnection
#             from .tasks import send_script
# 
#             protocol = "tcp"
#             WORKER_ENDPOINT = "%s://%s:%s" % (protocol, self.ip, str(self.port))
#             WORKER_SECRET_KEY = str(self.secret_key)
#             conn = BotConnection(WORKER_ENDPOINT, WORKER_SECRET_KEY)
#             conn.connect()
# 
#             req = {'type': 'ACC'}
#             resp = send_script(req, conn, REQUEST_TIMEOUT=1000, REQUEST_RETRIES=1)
#             conn.close()
# 
#             if resp and resp['type'] == 'ACK':
#                 return True
#         except Exception as e:
#             logger.error(e, exc_info=True)
#         return False
# 
#     def save(self, *args, **kwargs):
#         if not self.pk:  # first save
#             self.slug = random.randint(1000, 9999)
#             super(Worker, self).save(*args, **kwargs)
# 
#         s = str(self.owner.id) + "-" + str(self.id) + "-" + slugify(self.title)
#         self.slug = s[:50]
#         super(Worker, self).save(*args, **kwargs)
# 
#     @models.permalink
#     def get_absolute_url(self):
#         return ('core_worker_detail', (), {
#             'slug': self.slug})
# 
#     def permalink(self):
#         return reverse('core_worker_permalink', kwargs={'id': self.id})
# 
#     def __str__(self):
#         return self.title
# 
# Path: threebot/utils.py
# @login_required
# def get_my_orgs(request, an_user=None):
#     if request is not None and an_user is None:
#         an_user = request.user
# 
#     default_org, created = Organization.objects.get_or_create(slug='3bot', name="3bot")
# 
#     if not OrganizationUser.objects.filter(organization=default_org, user=an_user).exists():
#         # we create an OrganizationUser, so each user is member of our default_org
#         # if default_org was just created, we also mark this user as admin and create an OrganizationOwner
#         org_user = OrganizationUser(organization=default_org, user=an_user, is_admin=created)
#         org_user.save()
#         if created:
#             org_owner = OrganizationOwner(organization=default_org, organization_user=org_user)
#             org_owner.save()
# 
#     orgs = Organization.objects.filter(users=an_user)
# 
#     return orgs


from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from django.contrib.auth.decorators import login_required
from threebot.models import Worker
from threebot.utils import get_my_orgs



@login_required
def detail(request, id):
    orgs = get_my_orgs(request)

# Path: threebot/models.py
# class Worker(models.Model):
#     ACCESS_REQUEST_TIMEOUT = 1
#     STATUS_OFFLINE = 0
#     STATUS_ONLINE = 1
#     STATUS_BUSY = 9
#     STATUS_MUTED = 10
#     STATUS_CHOICES = (
#         (STATUS_OFFLINE, 'offline'),
#         (STATUS_ONLINE, 'online'),
#         (STATUS_BUSY, 'busy'),
#         (STATUS_MUTED, 'muted'),
#     )
# 
#     owner = models.ForeignKey(Organization, help_text="Worker owner")
#     title = models.CharField(max_length=255)
#     slug = models.SlugField(_('slug'), max_length=50, unique=True)
# 
#     date_created = models.DateTimeField(auto_now_add=True)
#     date_modified = models.DateTimeField(auto_now=True)
# 
#     ip = models.GenericIPAddressField("IP-Address",)
#     addr = models.CharField(max_length=200, null=True, blank=True, help_text='For now we use the IP to connect to the worker')
#     port = models.PositiveIntegerField(default=55555)
#     secret_key = models.CharField(max_length=200, null=True, blank=True, help_text='The Secret Key. Never share yours.')
# 
#     muted = models.BooleanField(default=False, help_text="Mute a Worker to prevent accessibility checks and improve performance.")
# 
#     pre_task = models.TextField(null=True, blank=True, help_text='this will run as a Script before the worker performs a workflow')
#     post_task = models.TextField(null=True, blank=True, help_text='this will run as a Script after the worker has performed a workflow')
# 
#     class Meta():
#         ordering = ['owner', 'title']
#         verbose_name = _("Worker")
#         verbose_name_plural = _("Workers")
# 
#     def get_status_display(self):
#         choices = dict(self.STATUS_CHOICES)
#         return choices[self.status]
# 
#     @cached_property
#     def status(self):
#         if self.muted:
#             return self.STATUS_MUTED
#         if self.is_busy:
#             return self.STATUS_BUSY
#         if self.is_accessible:
#             return self.STATUS_ONLINE
#         else:
#             return self.STATUS_OFFLINE
# 
#     @cached_property
#     def is_busy(self):
#         """Identifies is a Worfkflow is currently blocking this worker."""
#         return WorkflowLog.objects.filter(exit_code=WorkflowLog.PENDING, performed_on=self).exists()
# 
#     @cached_property
#     def is_accessible(self):
#         if self.muted:
#             return False
# 
#         try:
#             from .botconnection import BotConnection
#             from .tasks import send_script
# 
#             protocol = "tcp"
#             WORKER_ENDPOINT = "%s://%s:%s" % (protocol, self.ip, str(self.port))
#             WORKER_SECRET_KEY = str(self.secret_key)
#             conn = BotConnection(WORKER_ENDPOINT, WORKER_SECRET_KEY)
#             conn.connect()
# 
#             req = {'type': 'ACC'}
#             resp = send_script(req, conn, REQUEST_TIMEOUT=1000, REQUEST_RETRIES=1)
#             conn.close()
# 
#             if resp and resp['type'] == 'ACK':
#                 return True
#         except Exception as e:
#             logger.error(e, exc_info=True)
#         return False
# 
#     def save(self, *args, **kwargs):
#         if not self.pk:  # first save
#             self.slug = random.randint(1000, 9999)
#             super(Worker, self).save(*args, **kwargs)
# 
#         s = str(self.owner.id) + "-" + str(self.id) + "-" + slugify(self.title)
#         self.slug = s[:50]
#         super(Worker, self).save(*args, **kwargs)
# 
#     @models.permalink
#     def get_absolute_url(self):
#         return ('core_worker_detail', (), {
#             'slug': self.slug})
# 
#     def permalink(self):
#         return reverse('core_worker_permalink', kwargs={'id': self.id})
# 
#     def __str__(self):
#         return self.title
# 
# Path: threebot/utils.py
# @login_required
# def get_my_orgs(request, an_user=None):
#     if request is not None and an_user is None:
#         an_user = request.user
# 
#     default_org, created = Organization.objects.get_or_create(slug='3bot', name="3bot")
# 
#     if not OrganizationUser.objects.filter(organization=default_org, user=an_user).exists():
#         # we create an OrganizationUser, so each user is member of our default_org
#         # if default_org was just created, we also mark this user as admin and create an OrganizationOwner
#         org_user = OrganizationUser(organization=default_org, user=an_user, is_admin=created)
#         org_user.save()
#         if created:
#             org_owner = OrganizationOwner(organization=default_org, organization_user=org_user)
#             org_owner.save()
# 
#     orgs = Organization.objects.filter(users=an_user)
# 
#     return orgs


# Path: threebot/views/api/worker.py
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from django.contrib.auth.decorators import login_required
from threebot.models import Worker
from threebot.utils import get_my_orgs




@login_required
def detail(request, id):
    orgs = get_my_orgs(request)

    worker = get_object_or_404(Worker, owner__in=orgs, id=id)