import csv
from pathlib import Path
from django.core.management.base import BaseCommand, CommandError
from rcr.models import Item
import argparse

import csv

class DictReaderStrip(csv.DictReader):
    @property                                    
    def fieldnames(self):
        if self._fieldnames is None:
            # Initialize self._fieldnames
            # Note: DictReader is an old-style class, so can't use super()
            csv.DictReader.fieldnames.fget(self)
            if self._fieldnames is not None:
                self._fieldnames = [name.strip() for name in self._fieldnames]
        return self._fieldnames


class Command(BaseCommand):
    help = "Imports the RCR spreadsheet"

    def add_arguments(self, parser):
    #    parser.add_argument("poll_ids", nargs="+", type=int)
        parser.add_argument('--file', type=argparse.FileType('r'))


    def handle(self, *args, **options):
        #print(options)
        #path = Path(options["file"])
        #with open(path) as f:
                reader = DictReaderStrip(options["file"])
                #reader = csv.DictReader(f)
                for row in reader:
                    if row["Access count (all time)"] == "":
                        row["Access count (all time)"] = None
                    if row["Number of items"] == "":
                        row["Number of items"] = None
                    if row["Number of items"] == "Unknown":
                        row["Number of items"] = None

                    try:
                        item = Item.objects.get(rcr_platform_id=row["Unique Identifier"])

                        item.name=row["Name"]
                        item.description=row["Description"]
                        item.content_type=row["Content type"]
                        item.created_on=row["Created on"]
                        item.number_of_items=row["Number of items"]
                        item.specialty=row["Speciality"]
                        item.access_count=row["Access count (all time)"]
                        item.targeted_to_group=row["Targeted to group"]
                        item.review_link=row["Review link (if applicable)"]
                        item.review_link_password=row["Review link password (if applicable)"]

                        item.save()

                        self.stdout.write(
                            self.style.SUCCESS(f"Item updated: {item.pk}/{item.name}")
                        )
                    except Item.DoesNotExist:

                        item = Item.objects.create(
                             rcr_platform_id=row["Unique Identifier"],
                             name=row["Name"],
                             description=row["Description"],
                             content_type=row["Content type"],
                             created_on=row["Created on"],
                             number_of_items=row["Number of items"],
                             specialty=row["Speciality"],
                             access_count=row["Access count (all time)"],
                             targeted_to_group=row["Targeted to group"],
                             review_link=row["Review link (if applicable)"],
                             review_link_password=row["Review link password (if applicable)"],
                        )


                        self.stdout.write(
                            self.style.SUCCESS(f"Item created: {item.pk}/{item.name}")
                        )
