# coding=utf-8

import json
from rest_framework import serializers
from .models import Equipment

from utils.exceptions import CustomError
from apps.account.models import User


class EquipmentSerializer(serializers.ModelSerializer):
    type_text = serializers.CharField(source='type.name', read_only=True)
    supplier_text = serializers.CharField(source='supplier.name', read_only=True)
    location_text = serializers.SerializerMethodField()

    def get_location_text(self, obj):
        return obj.location.get_full_name()

    class Meta:
        model = Equipment
        fields = '__all__'

    def create(self, validated_data):
        validated_data['location_id'] = self.context['request'].data['location']
        validated_data['type_id'] = self.context['request'].data['type']
        validated_data['supplier_id'] = self.context['request'].data['supplier']
        instance = super(EquipmentSerializer, self).create(validated_data)
        return instance

    def update(self,instance, validated_data):
        validated_data['location_id'] = self.context['request'].data['location']
        validated_data['type_id'] = self.context['request'].data['type']
        validated_data['supplier_id'] = self.context['request'].data['supplier']
        instance = super(EquipmentSerializer, self).update(instance, validated_data)
        return instance
