from rest_framework import serializers
from .models import Field, OfficialKyosaiField, OfficialChusankanField


class OfficialKyosaiFieldSerializer(serializers.ModelSerializer):
    linked_field_names = serializers.SerializerMethodField()

    class Meta:
        model = OfficialKyosaiField
        fields = ['id', 'k_num', 's_num', 'address', 'kanji_name', 'area', 'linked_field_names']

    def get_linked_field_names(self, obj):
        return list(obj.fields.values_list('name', flat=True))


class OfficialChusankanFieldSerializer(serializers.ModelSerializer):
    linked_field_names = serializers.SerializerMethodField()

    class Meta:
        model = OfficialChusankanField
        fields = ['id', 'c_id', 'chusankan_flag', 'oaza', 'aza', 'chiban', 'branch_num',
                  'land_type', 'area', 'planting_area', 'original_crop', 'manager', 'owner',
                  'slope', 'base_amount', 'steep_slope_addition', 'smart_agri_addition',
                  'payment_amount', 'linked_field_names']

    def get_linked_field_names(self, obj):
        return list(obj.fields.values_list('name', flat=True))


class FieldSerializer(serializers.ModelSerializer):
    kyosai_fields = OfficialKyosaiFieldSerializer(many=True, read_only=True)
    chusankan_fields = OfficialChusankanFieldSerializer(many=True, read_only=True)

    class Meta:
        model = Field
        fields = ['id', 'name', 'address', 'area_tan', 'area_m2', 'owner_name', 'group_name', 'display_order', 'kyosai_fields', 'chusankan_fields']
