# coding=utf-8

from django.conf import settings
from rest_framework import serializers
from apps.usedvehicle.models import UsedVehicle, UsedVehicleImg
from apps.foundation.models import Option


class UsedVehicleSerializer(serializers.ModelSerializer):
    status_text = serializers.CharField(source='get_status_display', read_only=True)
    brand_name = serializers.CharField(source='brand.name', read_only=True)
    gearbox_name = serializers.CharField(source='gearbox.name', read_only=True)
    color_name = serializers.CharField(source='color.name', read_only=True)
    displacement_name = serializers.CharField(source='displacement.name', read_only=True)
    emission_name = serializers.CharField(source='emission.name', read_only=True)
    seat_count_name = serializers.CharField(source='seat_count.name', read_only=True)
    oil_type_name = serializers.CharField(source='emission.name', read_only=True)
    plate_date = serializers.DateField(format='%Y-%m-%d')
    factory_date = serializers.DateField(format='%Y-%m-%d')
    picture = serializers.SerializerMethodField()

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

    class Meta:
        model = UsedVehicle
        fields = '__all__'



class UsedVehicleDetailSerializer(serializers.ModelSerializer):
    status_text = serializers.CharField(source='get_status_display', read_only=True)
    brand_name = serializers.CharField(source='brand.name', read_only=True)
    gearbox_name = serializers.CharField(source='gearbox.name', read_only=True)
    color_name = serializers.CharField(source='color.name', read_only=True)
    displacement_name = serializers.CharField(source='displacement.name', read_only=True)
    emission_name = serializers.CharField(source='emission.name', read_only=True)
    seat_count_name = serializers.CharField(source='seat_count.name', read_only=True)
    oil_type_name = serializers.CharField(source='emission.name', read_only=True)
    plate_date = serializers.DateField(format='%Y-%m-%d')
    factory_date = serializers.DateField(format='%Y-%m-%d')
    images = serializers.SerializerMethodField()

    def get_images(self, obj):
        result = []
        rows = UsedVehicleImg.objects.filter(main=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


    class Meta:
        model = UsedVehicle
        fields = '__all__'