"""Operator for checking a clothes object."""

import bpy, os
from .....services import LogService
from .....services import LocationService
from .....services import ObjectService
from .....services import ClothesService
from .....services import MaterialService
from ...makeclothes import MakeClothesObjectProperties
from .....entities.objectproperties import GeneralObjectProperties
from .....entities.material.makeskinmaterial import MakeSkinMaterial
from ...makeclothes.operators.clothescommon import ClothesCommon
from ..... import ClassManager
from ....mpfboperator import MpfbOperator
from ....pollstrategy import pollstrategy, PollStrategy

_LOG = LogService.get_logger("makeclothes.checkclothes")

CLOTHES_CHECKS = dict()

@pollstrategy(PollStrategy.ANY_OBJECT_ACTIVE)
class MPFB_OT_CheckClothesOperator(MpfbOperator):
    """Perform basic sanity checks on the active object. You need to click this again if changing the clothes, the panel will not update automatically. Note that this operation might a long time depending on the number of vertex groups and the number of vertices"""
    bl_idname = "mpfb.check_makeclothes_clothes"
    bl_label = "Check"
    bl_options = {'REGISTER'}

    def get_logger(self):
        return _LOG

    def hardened_execute(self, context):

        basemesh = None
        clothes = None

        for obj in context.selected_objects:
            if ObjectService.object_is_basemesh(obj):
                basemesh = obj
            else:
                ot = ObjectService.get_object_type(obj)
                if ot and ot != "Skeleton":
                    clothes = obj

        if not basemesh:
            self.report({'ERROR'}, "No basemesh selected")
            return {'CANCELLED'}

        if not clothes:
            self.report({'ERROR'}, "No clothes selected")
            return {'CANCELLED'}

        uuid_value = GeneralObjectProperties.get_value("uuid", entity_reference=clothes)
        if not uuid_value:
            self.report({'ERROR'}, "No UUID found for the selected clothes")
            return {'CANCELLED'}

        try:
            CLOTHES_CHECKS[uuid_value] = ClothesService.mesh_is_valid_as_clothes(clothes, basemesh)
            self.report({'INFO'}, "Clothes check performed, see panel")
            return {'FINISHED'}
        except Exception as exc:
            _LOG.error("Clothes check failed with exception", exc)
            self.report({'ERROR'}, "Clothes check failed: " + str(exc))
            return {'CANCELLED'}

ClassManager.add_class(MPFB_OT_CheckClothesOperator)
