import logging
import re
from enum import Enum
import os.path

from django.conf import settings
from django.db import models

log = logging.getLogger(__name__)


class Product(models.Model):
    sap_id_regex = r'\b(\d{7})\b'
    id = models.CharField(max_length=20, db_column='id', primary_key=True)
    sap = models.CharField(max_length=10, db_column='material')
    season = models.CharField(max_length=10, db_column='season')
    season_ranking = models.DecimalField(max_digits=6, decimal_places=1)
    name = models.CharField(max_length=100, db_column='model')
    model = models.CharField(max_length=100, db_column='modelcode')
    gender = models.CharField(max_length=100, db_column='gender')
    category = models.CharField(max_length=100, db_column='category')
    family = models.CharField(max_length=100, db_column='product_family')
    color = models.CharField(max_length=100, db_column='colorway')

    class Meta:
        managed = False
        db_table = "keen_materials"

    @staticmethod
    def find_sap_ids(text):
        matches = re.finditer(Product.sap_id_regex, text)
        return [match.group(1) for match in matches]

    def serialize(self):
        return {
            'id': self.sap,
            'name': self.name,
            'model': self.model,
            'family': self.family,
            'gender': self.gender,
            'category': self.category,
            'color': self.color,
        }


class ProductImageFormat(Enum):
    THUMB_PNG = 'thumb.png'
    LARGE_JPG = 'large.jpg'
    LARGE_PNG = 'large.png'
    MED_JPG = 'med.jpg'
    MED_PNG = 'med.png'


class ProductImage:
    THUMB_DIR = os.path.join(settings.ASSET_DIR, 'products/thumbs')
    THUMB_URL = '/images/products/thumbs'
    # ordered by thumbnail preference
    VIEW_TYPES = ['C', '3Q', '3QL', '3QR', '3QRL', 'P', 'PL', 'P2', 'P2L',
                  'F3Q', 'L', 'PLA', 'PPS', 'PPS_WORN', 'PLD', 'OS', 'OSL',
                  'T', 'TL', 'PACK', 'F', 'B', 'INT', 'ALT_INT', 'FLR',
                  'FRONT', 'BACK']

    @staticmethod
    def get_image_path(sap, image_format):
        for view in ProductImage.VIEW_TYPES:
            path = os.path.join(ProductImage.THUMB_DIR,
                                '{}_{}-{}'.format(sap, view, image_format.value))
            if os.path.isfile(path):
                return path

    @staticmethod
    def get_image_url(sap, image_format):
        path = ProductImage.get_image_path(sap, image_format)
        if path:
            return path.replace(ProductImage.THUMB_DIR, ProductImage.THUMB_URL)



class SeasonRegionMaterial(models.Model):
    """Lists where and when a material is valid."""
    id = models.IntegerField(primary_key=True)
    material = models.CharField(max_length=10)
    season = models.CharField(max_length=4)
    region = models.CharField(max_length=20)
    ranking = models.IntegerField()

    class Meta:
        managed = False
        db_table = "keen_season_region_material"
