# coding=utf-8
from django.conf import settings
from rest_framework import serializers
from apps.vehicle.models import Series, Model, VehicleImg
from utils.booleancharfield import PriceShowCharField
from apps.store.models import Shop, StoreBrand

class SeriesSerializer(serializers.ModelSerializer):
    brand_name = serializers.CharField(source='brand.name', read_only=True)
    img = serializers.SerializerMethodField()

    def get_img(self, obj):
        if obj.thumbnail:
            return {'width': obj.thumbnail.width, 'height': obj.thumbnail.height, 'url': obj.thumbnail.get_path()}
        return ''


    class Meta:
        model = Series
        fields = '__all__'


class ModelSerializer(serializers.ModelSerializer):
    price = PriceShowCharField()
    sale_price = PriceShowCharField()

    class Meta:
        model = Model
        fields = '__all__'


class ModelDetailSerializer(serializers.ModelSerializer):
    series_name = serializers.CharField(source='series.name', read_only=True)
    brand_name = serializers.CharField(source='series.brand.name', read_only=True)
    img_url = serializers.SerializerMethodField()
    images = serializers.SerializerMethodField()
    stores = serializers.SerializerMethodField()
    price = PriceShowCharField()
    sale_price = PriceShowCharField()

    def get_img_url(self, obj):
        if obj.thumbnail:
            return {'width': obj.thumbnail.width, 'height': obj.thumbnail.height, 'url': obj.thumbnail.get_path()}
        return ''

    def get_images(self, obj):
        result = []
        rows = VehicleImg.objects.filter(vehicle_model=obj).values('img__picture', 'img__width', 'img__height')
        for row in rows:
            url = {'width': row['img__width'], 'height': row['img__height'],
                   'url': '%s%s%s' % (settings.SERVER_DOMAIN, settings.MEDIA_URL, row['img__picture'])}
            result.append(url)
        return result

    def get_stores(self, obj):
        result = []
        store_rows = StoreBrand.objects.filter(brand_id=obj.series.brand_id).values('store_id')
        shop_ids = [store_row['store_id'] for store_row in store_rows]
        rows = Shop.objects.filter(id__in=shop_ids, delete=False, enabled=True)
        for row in rows:
            item = {'name': row.name, 'addr': row.addr, 'tel': row.tel, 'img': ''}
            if row.img:
                item['img'] = '%s%s%s' % (settings.SERVER_DOMAIN, settings.MEDIA_URL, row.img.picture)
            result.append(item)
        return result

    class Meta:
        model = Model
        fields = '__all__'