from django.db import models
import os, errno

from api.utils import *


class ResultManager(models.Manager):
    def statistic(self, user):
      results = user.own_results.all()
      return {
          'amount': len(results),
      }

class Result(models.Model):
    name = models.CharField(default="untitled", max_length=64)
    create_time = models.DateTimeField(auto_now_add=True)
    update_time = models.DateTimeField(auto_now=True)

    progress = models.IntegerField(default=0)
    nodeFile = models.ForeignKey(to="api.File", on_delete=models.CASCADE, related_name="own_results_node", blank=True, null=True)
    edgeFile = models.ForeignKey(to="api.File", on_delete=models.CASCADE, related_name="own_results_edge", blank=True, null=True)
    
    # 注意plan和result的一对一，反向名为单数形式
    plan = models.OneToOneField(to="api.plan", on_delete=models.DO_NOTHING, related_name="own_result")

    mission = models.ForeignKey(to="api.Mission", on_delete=models.CASCADE, related_name="own_results")
    user = models.ForeignKey(to="api.User", on_delete=models.CASCADE, related_name='own_results')
    
    objects = ResultManager()

    class Meta:
        app_label = 'api'