from django.shortcuts import render

# Create your views here.
from django_filters.views import FilterView
from django.urls import reverse_lazy, reverse
from django.views.generic import (
    ListView,
    DetailView,
    CreateView,
    UpdateView,
    DeleteView,
)
from django.core.paginator import Paginator
from .models import Data, DataMs, TbFgPressinfoLotlist, LotSummary, DataRl, DataWb, LotSummaryRl, \
        RotateData, LotSummaryWb, Manualsize
from .filters import DataFilter, DataMsFilter, TbFgPressFilter, LotSummaryFilter, \
        DataRlFilter, DataWbFilter, LotSummaryRlFilter, LotSummaryWbFilter, RotateDataFilter, ManualsizeFilter
from django.urls import reverse
from django.contrib import messages
from pprint import pprint
from core.models import VMasterView, MgMasterView, BelMasterView, EMasterView, \
        AllProductDimensionForInsProcess, RotateBrokenTest
from core.filters import VMasterViewFilter, MgMasterViewFilter, BelMasterViewFilter, EMasterViewFilter,\
        AllProductDimensionForInsProcessFilter, RotateBrokenTestFilter

from core.utils import ConfigurableCRUDView

class DataListView(FilterView, ListView):
    model = Data
    template_name = 'legacy/data_list.html'
    ordering = ['-id', 'row_no']  # Order by id (ascending), then row_no (ascending)
    # context_object_name = 'data_list'
    paginate_by = 50  # Enable pagination

    # Specify the filter class
    filterset_class = DataFilter


    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # Pass model fields to the template
        context['fields'] = [field for field in self.model._meta.get_fields()]
        context['bs'] = [
            {'label': 'Dashboard', 'url': reverse('dashboard:index')},
            {'label': 'Data', 'url': reverse('legacy:data-list')},
        ]
        return context

# Read (detail view)
class DataDetailView(DetailView):
    model = Data
    template_name = 'data_detail.html'
    context_object_name = 'data'  # Use this name in templates


# Create
class DataCreateView(CreateView):
    model = Data
    template_name = 'legacy/data_form.html'
    fields = '__all__'  # Use all fields or specify a list of fields

    def form_valid(self, form):
        response = super().form_valid(form)
        messages.success(self.request, "Data has been successfully created!")
        return response
    
    def get_success_url(self):
        # Redirect to the edit page of the newly created object
        return reverse('legacy:data-update', kwargs={'pk': self.object.pk})


    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # Pass model fields to the template
        context['bs'] = [
            {'label': 'Dashboard', 'url': reverse('dashboard:index')},
            {'label': 'Data', 'url': reverse('legacy:data-list')},
            {'label': 'Data Create', 'url': reverse('legacy:data-create')},
        ]
        return context

# Update
class DataUpdateView(UpdateView):
    model = Data
    template_name = 'legacy/data_form.html'
    fields = '__all__'  # Use all fields or specify a list of fields
    
    def get_success_url(self):
        # Redirect to the edit page of the newly created object
        return reverse('legacy:data-update', kwargs={'pk': self.object.pk})

    def form_valid(self, form):
        response = super().form_valid(form)
        messages.success(self.request, "Data has been successfully updated!")
        return response


    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # Pass model fields to the template
        context['bs'] = [
            {'label': 'Dashboard', 'url': reverse('dashboard:index')},
            {'label': 'Data', 'url': reverse('legacy:data-list')},
            {'label': self.object, 'url': reverse('legacy:data-update', kwargs={'pk':self.object.pk})},
        ]
        return context

# Delete
class DataDeleteView(DeleteView):
    model = Data
    template_name = 'legacy/data_confirm_delete.html'
    success_url = reverse_lazy('legacy:data-list')  # Redirect after deletion

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # Pass model fields to the template
        context['bs'] = [
            {'label': 'Dashboard', 'url': reverse('dashboard:index')},
            {'label': 'Data', 'url': reverse('legacy:data-list')},
            {'label': self.object, 'url': reverse('legacy:data-update', kwargs={'pk':self.object.pk})},
        ]
        return context


class DataMsCRUDView(ConfigurableCRUDView):
    model = DataMs
    list_template_name = 'legacy/datacrud_list.html'
    detail_template_name = 'legacy/datacrud_detail.html'
    form_template_name = 'legacy/datacrud_form.html'
    confirm_delete_template_name = 'legacy/datacrud_confirm_delete.html'
    filterset_class = DataMsFilter

    page_title = "Data Measurement"

    # URL name mappings
    list_url_name = 'legacy:datams-list'
    create_url_name = 'legacy:datams-create'
    update_url_name = 'legacy:datams-update'
    delete_url_name = 'legacy:datams-delete'
    excludes = ["splitdata"]
    config_field_orders = ["id", "lot_no", "code"]  # Display these fields first
    ordering = ['-id',]

class TbFgPressInfoLotListCRUDView(ConfigurableCRUDView):
    model = TbFgPressinfoLotlist
    list_template_name = 'legacy/datacrud_list.html'
    detail_template_name = 'legacy/datacrud_detail.html'
    form_template_name = 'legacy/datacrud_form.html'
    confirm_delete_template_name = 'legacy/datacrud_confirm_delete.html'
    filterset_class = TbFgPressFilter

    page_title = "Fg Press"

    # URL name mappings
    list_url_name = 'legacy:fg-list'
    create_url_name = 'legacy:fg-create'
    update_url_name = 'legacy:fg-update'
    delete_url_name = 'legacy:fg-delete'
    config_field_orders = ["productcode", "product_year"]  # Display these fields first

class LotSummaryCRUDView(ConfigurableCRUDView):
    model = LotSummary
    list_template_name = 'legacy/datacrud_list.html'
    detail_template_name = 'legacy/datacrud_detail.html'
    form_template_name = 'legacy/datacrud_form.html'
    confirm_delete_template_name = 'legacy/datacrud_confirm_delete.html'
    filterset_class = LotSummaryFilter

    page_title = "Lot Summary"

    # URL name mappings
    list_url_name = 'legacy:ls-list'
    create_url_name = 'legacy:ls-create'
    update_url_name = 'legacy:ls-update'
    delete_url_name = 'legacy:ls-delete'
    config_fields = ["id", "lot_no", "code", "avg", "start_time", "end_time", "grade", "created_at"]  # Display these fields first
    config_field_orders = ["id", "lot_no", "code", "avg", "start_time", "end_time", "grade", "created_at"]  # Display these fields first
    config_readonly_fields = ["lot_no"]
    # config_edit_fields = ["lot_no", "code"]
    ordering = ["-created_at", "-id",]

class VMasterViewCRUDView(ConfigurableCRUDView):
    """
    CRUD view for managing VMasterView objects.
    """
    model = VMasterView
    list_template_name = 'legacy/datacrud_list.html'
    detail_template_name = 'legacy/datacrud_detail.html'
    form_template_name = 'legacy/datacrud_form.html'
    confirm_delete_template_name = 'legacy/datacrud_confirm_delete.html'
    filterset_class = VMasterViewFilter  # Replace with the appropriate filter class if needed

    # Page title and URL mappings
    page_title = "VMaster View"
    list_url_name = 'legacy:vm-list'
    create_url_name = 'legacy:vm-create'
    update_url_name = 'legacy:vm-update'
    delete_url_name = 'legacy:vm-delete'

    # Configuration for fields
    # config_fields = ["id", "code", "description", "created_at", "updated_at"]
    # config_field_orders = ["id", "code", "description", "created_at", "updated_at"]
    # config_readonly_fields = ["id", "created_at"]

    # Default ordering
    # ordering = ["-created_at", "-id"]

class MgMasterViewCRUDView(ConfigurableCRUDView):
    """
    CRUD view for managing MgMasterView objects.
    """
    model = MgMasterView
    list_template_name = 'legacy/datacrud_list.html'
    detail_template_name = 'legacy/datacrud_detail.html'
    form_template_name = 'legacy/datacrud_form.html'
    confirm_delete_template_name = 'legacy/datacrud_confirm_delete.html'
    filterset_class = MgMasterViewFilter  # Replace with the appropriate filter class if needed

    # Page title and URL mappings
    page_title = "MgMaster View"
    list_url_name = 'legacy:mg-list'
    create_url_name = 'legacy:mg-create'
    update_url_name = 'legacy:mg-update'
    delete_url_name = 'legacy:mg-delete'

    # Configuration for fields
    # config_fields = [
        # "id", "PRO0", "PRO1", "PRO1C", "PRO2", "PRO5", 
        # "PRO8", "PRO9", "PRO10", "PRO11", "PRO12"
    # ]
    # config_field_orders = [
        # "id", "PRO0", "PRO1", "PRO1C", "PRO2", "PRO5", 
        # "PRO8", "PRO9", "PRO10", "PRO11", "PRO12"
    # ]
    # config_readonly_fields = ["id"]

    # Default ordering
    # ordering = ["-id", "PRO2"]

class BelMasterViewCRUDView(ConfigurableCRUDView):
    """
    CRUD view for managing BelMasterView objects.
    """
    model = BelMasterView
    list_template_name = 'legacy/datacrud_list.html'
    detail_template_name = 'legacy/datacrud_detail.html'
    form_template_name = 'legacy/datacrud_form.html'
    confirm_delete_template_name = 'legacy/datacrud_confirm_delete.html'
    filterset_class = BelMasterViewFilter  # Replace with the appropriate filter class if needed

    # Page title and URL mappings
    page_title = "BelMaster View"
    list_url_name = 'legacy:bel-list'
    create_url_name = 'legacy:bel-create'
    update_url_name = 'legacy:bel-update'
    delete_url_name = 'legacy:bel-delete'

    # Configuration for fields
    # config_fields = [
        # "id", "PRO0", "PRO1", "PRO1C", "PRO2", "PRO5",
        # "PRO8", "PRO9", "PRO10", "PRO11", "PRO12", "MC11",
        # "MC12", "MC14", "MC15", "MC16", "MC19", "MC20", "MC21"
    # ]
    # config_field_orders = [
        # "id", "PRO0", "PRO1", "PRO1C", "PRO2", "PRO5",
        # "PRO8", "PRO9", "PRO10", "PRO11", "PRO12", "MC11",
        # "MC12", "MC14", "MC15", "MC16", "MC19", "MC20", "MC21"
    # ]
    # config_readonly_fields = ["id"]

    # Default ordering
    # ordering = ["-id", "PRO2"]

class EMasterViewCRUDView(ConfigurableCRUDView):
    """
    CRUD view for managing EMasterView objects.
    """
    model = EMasterView
    list_template_name = 'legacy/datacrud_list.html'
    detail_template_name = 'legacy/datacrud_detail.html'
    form_template_name = 'legacy/datacrud_form.html'
    confirm_delete_template_name = 'legacy/datacrud_confirm_delete.html'
    filterset_class = EMasterViewFilter  # Replace with the appropriate filter class

    # Page title and URL mappings
    page_title = "EMaster View"
    list_url_name = 'legacy:em-list'
    create_url_name = 'legacy:em-create'
    update_url_name = 'legacy:em-update'
    delete_url_name = 'legacy:em-delete'

    # Configuration for fields
    # config_fields = [
        # "id", "PRO0", "PRO1", "PRO1C", "PRO2", "PRO5",
        # "PRO8", "PRO9", "PRO10", "PRO11", "PRO12", "PRO13",
        # "PRO14", "PRO15", "PRO16", "PRO17", "PRO18", "PRO21",
        # "PRO25", "PRO27"
    # ]
    # config_field_orders = [
        # "id", "PRO0", "PRO1", "PRO1C", "PRO2", "PRO5",
        # "PRO8", "PRO9", "PRO10", "PRO11", "PRO12", "PRO13",
        # "PRO14", "PRO15", "PRO16", "PRO17", "PRO18", "PRO21",
        # "PRO25", "PRO27"
    # ]
    # config_readonly_fields = ["id"]

    # Default ordering
    # ordering = ["-id", "PRO2"]
    
class DataRLCRUDView(ConfigurableCRUDView):
    model = DataRl
    list_template_name = 'legacy/datacrud_list.html'
    detail_template_name = 'legacy/datacrud_detail.html'
    form_template_name = 'legacy/datacrud_form.html'
    confirm_delete_template_name = 'legacy/datacrud_confirm_delete.html'
    filterset_class = DataRlFilter

    page_title = "Data RL"

    # URL name mappings
    list_url_name = 'legacy:datarl-list'
    create_url_name = 'legacy:datarl-create'
    update_url_name = 'legacy:datarl-update'
    delete_url_name = 'legacy:datarl-delete'
    # excludes = ["splitdata"]
    config_field_orders = ["id", "lot_no", "code"]  # Display these fields first
    ordering = ["-id"]

class DataWbCRUDView(ConfigurableCRUDView):
    model = DataWb
    list_template_name = 'legacy/datacrud_list.html'
    detail_template_name = 'legacy/datacrud_detail.html'
    form_template_name = 'legacy/datacrud_form.html'
    confirm_delete_template_name = 'legacy/datacrud_confirm_delete.html'
    filterset_class = DataWbFilter

    page_title = "Data WB"

    # URL name mappings
    list_url_name = 'legacy:datawb-list'
    create_url_name = 'legacy:datawb-create'
    update_url_name = 'legacy:datawb-update'
    delete_url_name = 'legacy:datawb-delete'
    # excludes = ["splitdata"]
    config_field_orders = ["id", "lot_no", "code"]  # Display these fields first
    ordering = ["-id"]

class LotSummaryRlCRUDView(ConfigurableCRUDView):
    model = LotSummaryRl
    list_template_name = 'legacy/datacrud_list.html'
    detail_template_name = 'legacy/datacrud_detail.html'
    form_template_name = 'legacy/datacrud_form.html'
    confirm_delete_template_name = 'legacy/datacrud_confirm_delete.html'
    filterset_class = LotSummaryRlFilter

    page_title = "Lot Summary RL"

    # URL name mappings
    list_url_name = 'legacy:lsrl-list'
    create_url_name = 'legacy:lsrl-create'
    update_url_name = 'legacy:lsrl-update'
    delete_url_name = 'legacy:lsrl-delete'
    # excludes = ["splitdata"]
    config_field_orders = ["id", "lot_no", "code"]  # Display these fields first

class LotSummaryWbCRUDView(ConfigurableCRUDView):
    model = LotSummaryWb
    list_template_name = 'legacy/datacrud_list.html'
    detail_template_name = 'legacy/datacrud_detail.html'
    form_template_name = 'legacy/datacrud_form.html'
    confirm_delete_template_name = 'legacy/datacrud_confirm_delete.html'
    filterset_class = LotSummaryWbFilter

    page_title = "Lot Summary WB"

    # URL name mappings
    list_url_name = 'legacy:lswb-list'
    create_url_name = 'legacy:lswb-create'
    update_url_name = 'legacy:lswb-update'
    delete_url_name = 'legacy:lswb-delete'
    # excludes = ["splitdata"]
    config_field_orders = ["id", "lot_no", "code"]  # Display these fields first

class RotateDataCRUDView(ConfigurableCRUDView):
    model = RotateData
    list_template_name = 'legacy/datacrud_list.html'
    detail_template_name = 'legacy/datacrud_detail.html'
    form_template_name = 'legacy/datacrud_form.html'
    confirm_delete_template_name = 'legacy/datacrud_confirm_delete.html'
    filterset_class = RotateDataFilter

    page_title = "Rotate Data"

    # URL name mappings
    list_url_name = 'legacy:rotate-list'
    create_url_name = 'legacy:rotate-create'
    update_url_name = 'legacy:rotate-update'
    delete_url_name = 'legacy:rotate-delete'
    # excludes = ["splitdata"]
    config_field_orders = ["id", "lot_no", "code"]  # Display these fields first

class ManualsizeCRUDView(ConfigurableCRUDView):
    model = Manualsize
    list_template_name = 'legacy/datacrud_list.html'
    detail_template_name = 'legacy/datacrud_detail.html'
    form_template_name = 'legacy/datacrud_form.html'
    confirm_delete_template_name = 'legacy/datacrud_confirm_delete.html'
    
    filterset_class = ManualsizeFilter  # If you have a filter for this model

    page_title = "Manual Size Data"

    # URL name mappings
    list_url_name = 'legacy:manualsize-list'
    create_url_name = 'legacy:manualsize-create'
    update_url_name = 'legacy:manualsize-update'
    delete_url_name = 'legacy:manualsize-delete'

    # Define the order of fields to be displayed
    config_field_orders = ["lotno", "size_name", "std", "tolun", "tolup", "created_at", "productcode"]

class AllProductDimensionForInsProcessCRUDView(ConfigurableCRUDView):
    model = AllProductDimensionForInsProcess
    list_template_name = 'legacy/datacrud_list.html'
    detail_template_name = 'legacy/datacrud_detail.html'
    form_template_name = 'legacy/datacrud_form.html'
    confirm_delete_template_name = 'legacy/datacrud_confirm_delete.html'

    filterset_class = AllProductDimensionForInsProcessFilter  # If a filter is needed

    page_title = "All Product Dimension for Inspection Process"

    # URL name mappings
    list_url_name = 'legacy:allproductdimension-list'
    create_url_name = 'legacy:allproductdimension-create'
    update_url_name = 'legacy:allproductdimension-update'
    delete_url_name = 'legacy:allproductdimension-delete'

    # Define the order of fields to be displayed
    # config_field_orders = ["ProdType", "ProductCode", "Size_Id", "Size_Name", "Std", "TolUn", "TolUp"]

    # Exclude fields if necessary
class RotateBrokenTestCRUDView(ConfigurableCRUDView):
    model = RotateBrokenTest
    list_template_name = 'legacy/datacrud_list.html'
    detail_template_name = 'legacy/datacrud_detail.html'
    form_template_name = 'legacy/datacrud_form.html'
    confirm_delete_template_name = 'legacy/datacrud_confirm_delete.html'

    filterset_class = RotateBrokenTestFilter  # If a filter is needed, else remove this line

    page_title = "Rotate Broken Test Data"

    # URL name mappings
    list_url_name = 'legacy:rotatebrokentest-list'
    create_url_name = 'legacy:rotatebrokentest-create'
    update_url_name = 'legacy:rotatebrokentest-update'
    delete_url_name = 'legacy:rotatebrokentest-delete'

    # Define the order of fields to be displayed
    config_field_orders = ["id", "lot_no", "code", "row_no", "speed_spec", "speed_test", "speedOk",
                           "qty", "station_no", "created_at", "updated_at", 
                            "machine_id",  "emp_id", "devid", "mode", "cal_mode"]
    ordering = ['-id',]
