from __future__ import unicode_literals

import json

from django.core import serializers
from django.db import models

from datetime import datetime


# https://docs.djangoproject.com/en/1.10/topics/db/queries/
# Create your models here.

class SoftwareList(models.Model):
    product = models.CharField(max_length=100)

    def __unicode__(self):
        return str(self.product)


class CVSSBaseMetric(models.Model):
    score = models.DecimalField(max_length=20, decimal_places=2, max_digits=10, default=0.0)
    access_vector = models.CharField(max_length=30)
    access_complexity = models.CharField(max_length=30)
    authentication = models.CharField(max_length=30)
    confidentiality_impact = models.CharField(max_length=30)
    integrity_impact = models.CharField(max_length=30)
    availability_impact = models.CharField(max_length=30)
    source = models.CharField(max_length=50)
    generated_datetime = models.DateTimeField(max_length=30, default=datetime.now)

    def __unicode__(self):
        return str(self.score)


class Reference(models.Model):
    source_name = models.CharField(max_length=50, default="")
    source_type = models.CharField(max_length=30)
    source_url = models.CharField(max_length=1000, default="")
    source_text = models.CharField(max_length=1050, default="")

    def __repr__(self):
        return self.source_name

    def __unicode__(self):
        return self.source_name + ' ' + self.source_text


class CVEEntry(models.Model):
    cve_id = models.CharField(max_length=30, unique=True)
    published_time = models.DateTimeField(max_length=30, default=datetime.now)
    last_modified_time = models.DateTimeField(max_length=30, editable=True)
    security_protection = models.CharField(max_length=100)
    cwe = models.CharField(max_length=30, null=True, blank=True)
    summary = models.CharField(max_length=2050)
    software_list = models.ManyToManyField(SoftwareList)
    reference = models.ManyToManyField(Reference)
    cvss_base_metrics = models.ForeignKey(CVSSBaseMetric, blank=True, null=True)

    # def save(self, *args, **kwargs):
    #     self.last_modified_time = datetime.now()
    #     super(CVEEntry, self).save(*args, **kwargs)

    def get_cvsss_score(self):
        return self.cvss_base_metrics.score if self.cvss_base_metrics else None

    def get_affected__product(self):
        product = "".join([p for p in self.software_list.all()][0].product)
        return product

    def __unicode__(self):
        return self.cve_id

    class Meta:
        verbose_name = "CVE Entry"
        verbose_name_plural = "CVE Entries"






