import os
import csv
import tempfile
from pathlib import Path
from os.path import basename, dirname, realpath, abspath

from django.core.management.base import BaseCommand, CommandError
from django.conf import settings

from products.models import Product, SeasonRegionMaterial, UPC, ProductImage, ProductImageFormat



class Command(BaseCommand):
    help = 'Send a product feed to Locally'


    def add_arguments(self, parser):
        parser.add_argument('season')


    def handle(self, *args, **options):
        season = options['season']
        for region in ['US', 'CANADA', 'UTILITY US', 'UTILITY CANADA']:
            upcs = self.get_upcs(season, region)
            self.write_csv(self.csv_path(season, region), upcs, season)


    def get_upcs(self, season, region):
        srms = SeasonRegionMaterial.objects.filter(season=season, region__iexact=region).distinct('material')
        materials = [srm.material for srm in srms]
        return UPC.objects.filter(material__in=materials).distinct('upc')


    def csv_path(self, season, region):
        csv_dir = os.path.join(settings.ASSET_DIR, 'locally')
        filename = f'Keen_{season}_{region}.csv'.replace(' ', '_')
        return os.path.join(csv_dir, filename)


    def write_csv(self, path, upcs, season):
        Path(dirname(path)).mkdir(parents=True, exist_ok=True)
        with open(path, 'w', newline='') as csvfile:
            writer = csv.writer(csvfile) #, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
            writer.writerow(self.upc_headers())
            for upc in upcs:
                prod = self.get_product(upc, season)
                if prod:
                    writer.writerow(self.upc_data(season, upc, prod))


    def get_product(self, upc, season):
        prods = Product.objects.filter(sap=upc.material, season=season)
        prod = None
        if len(prods) == 1:
            prod = prods[0]
        elif len(prods) > 1:
            self.notice(f'{upc.upc}: {len(prods)} prods for {upc.material}/{season} - using first')
            prod = prods[0]
        else:
            # product may not be in current season, so find the most
            # recent one.  "shouldn't happen"
            prods = Product.objects.filter(sap=upc.material).order_by('-season_ranking')
            if len(prods) > 0:
                self.notice(f'{upc.upc}: no prods for {upc.material}/{season} - {len(prods)} in all seasons')
                prod = prods[0]
            else:
                self.notice(f'{upc.upc}: no prods for {upc.material} in any season')

        return prod


    def upc_headers(self):
        return [
            "Style Number",
            "Name",
            "Color",
            "Division",
            "Gender",
            "Category",
            "Description",
            "Size Range",
            #"Wholesale CAD",
            #"Retail CAD",
            "Wholesale USD",
            "Retail USD",
            "Size 1",
            "UPC 1",
            "Image URL",
        ]


    def upc_data(self, season, upc, prod):
        return [
            upc.material,
            prod.name.lower(),
            prod.color.lower(),
            "footwear",
            prod.gender.lower(),
            prod.category.lower(),
            self.description(prod),
            prod.size_range,
            #"Wholesale CAD",
            #"Retail CAD",
            prod.wholesale,
            prod.retail,
            upc.size_grid,
            upc.upc,
            self.image_url(upc.material),
        ]


    def description(self, prod):
        descr = None
        callouts = [f for f in Product._meta.fields if f.name.startswith('tech_call_out')]
        for c in callouts:
            v = c.value_from_object(prod)
            if v:
                if descr:
                    descr += f'<br>* {v}'
                else:
                    descr = f'* {v}'
        return descr


    def image_url(self, material):
        views = ['P', 'P2', 'PLA', 'FRONT'] # only want side views
        paths = ProductImage.get_all_image_urls(material, ProductImageFormat.MED_JPG,
                                                view_types=views, full_url=True)
        if len(paths) > 0:
            return paths[0]
        else:
            return ''


    def notice(self, s):
        self.stdout.write(self.style.NOTICE(s))
