from datetime import timedelta

from django.db import models


# TODO: comment classes


class Signs(models.Model):
    sign_id = models.AutoField(primary_key=True, unique=True)
    text = models.CharField(max_length=300)


class Types(models.Model):
    type_id = models.AutoField(primary_key=True, unique=True)
    type = models.CharField(max_length=300)


class Emails(models.Model):
    email_id = models.AutoField(primary_key=True, unique=True)
    subject = models.TextField()
    sender = models.TextField()
    recipient = models.TextField()
    date = models.TextField()
    cc = models.TextField()
    body = models.TextField()
    type = models.ForeignKey(Types, on_delete=models.PROTECT)
    sign = models.ManyToManyField(Signs)

    def __str__(self):
        return self.body


class GameRuns(models.Model):
    gamerun_id = models.AutoField(primary_key=True, unique=True)
    session_id = models.CharField(max_length=200)
    player_name = models.CharField(max_length=100)
    emails = models.ManyToManyField(Emails, through='EmailGameRuns')
    start_time = models.DateTimeField(auto_now_add=True)
    end_time = models.DateTimeField(null=True)


class EmailGameRuns(models.Model):
    email = models.ForeignKey(Emails, on_delete=models.CASCADE)
    game_run = models.ForeignKey(GameRuns, on_delete=models.CASCADE)
    order = models.IntegerField(default=0)

    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=order):
        if self.order == 0:
            try:
                recent = EmailGameRuns.objects.filter(
                    game_run__exact=self.game_run
                ).order_by(
                    '-order'
                )[0]
                self.order = recent.order + 1
            except IndexError:
                self.order = 1

        super(EmailGameRuns, self).save(force_insert, force_update)

    player_answer = models.BooleanField(null=True)
    duration = models.DurationField(default=timedelta())

class Settings(models.Model):
    setting_id = models.AutoField(primary_key=True, unique=True)
    item = models.CharField(max_length=100)
    value = models.IntegerField(default=0)
