from django.contrib.auth.decorators import login_required
from rest_framework import status
from rest_framework.response import Response
from rest_framework.parsers import JSONParser
from django.http.response import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from .models import ProductsModel, LinesModel, SachetDefectsModel
from .serializers import ProductSerializer, LineSerializer, SachetDefectSerializer
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import api_view, renderer_classes, authentication_classes, permission_classes

from django.views.generic import ListView, CreateView
from django.http import Http404
from django.shortcuts import get_object_or_404
from django.urls import reverse, reverse_lazy
from .forms import ProductsModelForm, LinesModelForm

""" SACHET MACHINES DEFECTS VIEWS ==============================================================  """
from .models import SachetDefectsModel
class SachetDefectListView(ListView):
    context_object_name = 'data'
    login_required = True
    queryset = SachetDefectsModel.objects.all().order_by('-id')
    template_name = 'defect/list.html'



class SachetDefectCreateView(CreateView):
    model = SachetDefectsModel
    login_required = True
    fields = ['defect_code', 'defect_description', 'defect_category']
    template_name = 'defect/create.html'

    def form_valid(self, form):
        if self.request.user.profile.role != 'INITIATOR':
            form.instance.created_by = self.request.user.username
            return super(SachetDefectCreateView, self).form_valid(form)
        raise Http404("User Not Allowed!!!")

    def get_success_url(self):
        return f"/utils/defect/list/"

""" SACHET MACHINE DEFECTS VIEWS ======================================================================"""