# -*- coding: utf-8 -*-
"""
Security API Source
"""
from datetime import timedelta
import dateutil.parser
from redteamcore import Resource
from elem.vulnerability import VulnerabilitySource
from elem.host import Rpm

class SecurityApiSource(VulnerabilitySource):
    def __init__(self, name, location, tlsverify=True, cache_location=None):
        super(SecurityApiSource, self).__init__(name,
                                                location,
                                                VulnerabilitySource.API_SOURCE,
                                                tlsverify,
                                                cache_location=cache_location)

    def cves(self):
        cve_result = dict()

        for cve in self.data:
            published_date = None
            if cve['public_date']:
                published_date = dateutil.parser.parse(cve['public_date']).replace(tzinfo=None).date()
            cve_result[cve['CVE']] = dict(published_date=str(published_date),
                                          source_name=self.name,
                                          source_type=self.source_type,
                                          affected_packages=[Rpm(package) for package in cve['affected_packages']])
        return cve_result


    def update_cves(self):
        cves = []

        update_resoure = Resource(self.after_url())
        new_data = update_resoure.read()

        for cve in new_data:
            cves.append(cve['CVE'])
        return cves

    def latest_date(self):
        latest = dateutil.parser.parse('01-01-1970')
        for cve in self.data:
            if cve['public_date']:
                cve_date = dateutil.parser.parse(cve['public_date']).replace(tzinfo=None)
                if cve_date > latest:
                    latest = cve_date
        return latest.date()

    def after_date(self):
        return self.latest_date() + timedelta(days=1)

    def after_url(self):
        if '?' in self.location:
            return self.location + '&after=' + str(self.after_date())
        return self.location + '?after=' + str(self.after_date())
