import bpy
import bmesh
import os
from ..utils import exporter
from ..cAPI import SimulationAPI
import numpy as np

class HI_PHY_OT_ConvertUV(bpy.types.Operator):
    bl_idname = "hi_phy.convert_uv"
    bl_label = "Hi Phy Convert UV"
    bl_options = {'REGISTER', 'UNDO_GROUPED'}
    obj: bpy.props.StringProperty(
        default='',
        name='Mesh'
    )
    def execute(self, context):
        mesh = context.scene.objects[self.obj]
        if not mesh or mesh.type != 'MESH':
            self.report({"ERROR"}, "No valid mesh object")
            return {'CANCELLED'}

        bpy.ops.object.mode_set(mode='EDIT')
        n_verts = mesh.data.attributes.domain_size('POINT')
        uvs = np.zeros((n_verts, 3), dtype=np.float32)
        bm = bmesh.from_edit_mesh(mesh.data)
        uv_layer = bm.loops.layers.uv.active
        for vert in bm.verts:
            for loop in vert.link_loops:
                uvs[vert.index][0] = loop[uv_layer].uv[0]
                uvs[vert.index][1] = loop[uv_layer].uv[1]

        # We can't update the attribute of an editing mesh.
        # Get into object mpde
        bpy.ops.object.mode_set(mode='OBJECT')

        uv_attr = mesh.data.attributes.get('hi_phy_cloth_uv')
        if not uv_attr:
            uv_attr = mesh.data.attributes.new("hi_phy_cloth_uv", 'FLOAT_VECTOR', 'POINT')

        uv_attr.data.foreach_set("vector", np.ravel(uvs))
        mesh.data.update()
        return {'FINISHED'}
        
__CLASSES__ = [
    HI_PHY_OT_ConvertUV
]

def register():
    for class_ in __CLASSES__:
        bpy.utils.register_class(class_)


def unregister():
    for class_ in reversed(__CLASSES__):
        bpy.utils.unregister_class(class_)
