from webmote_django.webmote.models import *
from django.db import models
from django.contrib.auth.models import User
from django.forms import ModelForm
from django import forms
from django.forms.widgets import *
from crontab import CronTab

###########
# Schedules
###########

class Schedules(models.Model):
    name = models.CharField(max_length=100, blank=True)
    active = models.BooleanField()
    class Meta:
        app_label = 'webmote'

    def delete(self, *args, **kwargs):
        for schedlet in self.schedlet_set.all():
            schedlet.delete()
        super(Schedules, self).delete(*args, **kwargs)

class Schedule_Form(ModelForm):
    name = forms.CharField(required=False, widget=forms.TextInput(attrs={'placeholder': 'e.g. AC, Heat, Lights, etc.'}))
    class Meta:
        model = Schedules
        app_label = 'webmote'
        exclude = ('active',)
##########
# Schedlet
##########

class Schedlet(models.Model):
    schedule = models.ForeignKey(Schedules)
    action = models.ForeignKey(Actions, related_name='schedlet_action')
    time = models.TimeField()
    sunday = models.BooleanField()
    monday = models.BooleanField()
    tuesday = models.BooleanField()
    wednesday = models.BooleanField()
    thursday = models.BooleanField()
    friday = models.BooleanField()
    saturday = models.BooleanField()
    class Meta:
        app_label = 'webmote'

    def save(self, *args, **kwargs):
        super(Schedlet, self).save(*args, **kwargs)
        # the port number here should be obtained dynamically
        cmd = 'wget http://localhost:8081/scheduler/runSchedlet/' + str(self.id) + '/'
        tab = CronTab()
        job = tab.new(command=cmd, comment='Generated by Webmote')
        job.minute.on(self.time.minute)
        job.hour.on(self.time.hour)
        days = (
            self.sunday,
            self.monday,
            self.tuesday, 
            self.wednesday,
            self.thursday,
            self.friday,
            self.saturday
        )
        for (num, day) in enumerate(days):
            if day:
                job.dow.on(num)
                tab.write()

    def delete(self, *args, **kwargs):
        # the port number here should be obtained dynamically
        cmd = 'wget http://localhost:8081/scheduler/runSchedlet/' + str(self.id) + '/'
        tab = CronTab()
        job = tab.find_command(cmd)
        if job:
            tab.remove_all(cmd)
        tab.write()
        super(Schedlet, self).delete(*args, **kwargs)

class Schedlet_Form(ModelForm):
    time = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'e.g. 15:30, 1:30, etc.'}))
    class Meta:
        model = Schedlet
        app_label = 'webmote'
        exclude = ('schedule',)
