from collections import defaultdict
from dateutil.parser import parse as date_parse

from report.models import MostVulnerableChildrenVulnerabilityMarker
from report.utils import convert_to_int

from .common import get_or_create_project


def extract(csv_data, _):
    import_data = defaultdict(lambda: defaultdict(dict))

    # Collect Data
    for row in csv_data:
        p1_translation = row['Project']
        p2_translation = row['Project1']
        p3_translation = row['Project2']

        pj_number = convert_to_int(
            (p1_translation or p2_translation or p3_translation).split('-')[0]
        )
        p_date = date_parse(row['Textbox40'].split(':')[1].strip()).date()

        for field in MostVulnerableChildrenVulnerabilityMarker.FIELDS:
            value = convert_to_int(row[field])
            if value:
                import_data[pj_number][p_date][field] = value

    # Save Data to DB
    for pj_number, data in import_data.items():
        if pj_number is None:
            continue
        project = get_or_create_project(pj_number)
        for p_date, counts in data.items():
            obj, _ = MostVulnerableChildrenVulnerabilityMarker.objects.get_or_create(
                project=project,
                date=p_date,
            )
            obj.data = counts
            obj.save()
