from django.db import models

import webbrowser
import psutil


class Category (models.Model):
    name = models.CharField(max_length=255)

    def __unicode__(self):
        return self.name


class Url(models.Model):
    url = models.CharField(max_length=255)
    date = models.DateTimeField(auto_now_add=True)
    category = models.ForeignKey(Category)
    played = models.BooleanField(default=False)

    def __unicode__(self):
        return self.url


class Play(models.Model):
    actual = models.ForeignKey(Url, default=None)

    # J'ai des doutes sur la class Meta. Peut eter à enlever
    class Meta:
        abstract = True

    def save(self, *args, **kwargs):
        self.__class__.objects.exclude(id=self.id).delete()
        super(Play, self).save(*args, **kwargs)

    @classmethod
    def load():
        try:
            return Play.objects.get()
        except Play.DoesNotExist:
            return Play()

    def play_next(self):
        # bug si y'a pas de self.actual
        url = Url.objects.filter(date__lt=self.actual.date).first()
        if not url:
            return

        self.actual = url
        self.save()

        PROCNAME = 'firefox.exe'
        for proc in psutil.process_iter():
            if proc.name == PROCNAME:
                proc.kill()

        webbrowser.open(url.url)

    def reset(self):
        self.actual = Url.objects.filter(date__lt=self.actual.date).last()
        self.save()

@@ -958,39 +958,46 @@
     
-#%C2%A0bug si y'a pas de self.actual
+if not self.actual:%0A            return
 %0A   
@@ -1197,16 +1197,19 @@
 for proc
+ess
  in psut
@@ -1246,16 +1246,19 @@
  if proc
+ess
 .name ==
@@ -1288,16 +1288,19 @@
     proc
+ess
 .kill()%0A

fix play next without url