from django_filters import rest_framework as filters
from apps.mtm.models import Material, Step

from apps.wpm.services import WpmServies
from .models import Operation, WMaterial, WProduct

class WMaterialFilterSet(filters.FilterSet):

    operation = filters.NumberFilter(method='filter_operation')
    class Meta:
        model = WMaterial
        fields = ['material', 'subproduction_plan', 'subproduction_plan__process', 'subproduction_plan__workshop', 'operation']

    def filter_operation(self, queryset, name, value):
        operation = Operation.objects.get(pk=value)
        wproducts = WProduct.objects.filter(ow_wproduct__operation=value)
        step = operation.step
        if wproducts.exists():
            subplans = WpmServies.get_subplans_queryset_from_wproducts(wproducts)
        else:
            subplans = WpmServies.get_subplans_queyset_from_step(step)
        queryset = queryset.filter(subproduction_plan__in=subplans).exclude(material__type=Material.MA_TYPE_HALFGOOD)
        return queryset