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

class HI_PHY_OT_ConvertParticlesToPointCloud(bpy.types.Operator):
    bl_idname = "hi_phy.convert_particles_to_point_cloud"
    bl_label = "Hi Phy Convert Particles To Point Cloud"
    bl_options = {'REGISTER', 'UNDO_GROUPED'}

    def execute(self, context):
        depsgraph = bpy.context.evaluated_depsgraph_get()
        obj = bpy.context.object
        obj_eval = obj.evaluated_get(depsgraph)
        points = []
        for psys in obj_eval.particle_systems:
            # Access particles
            for p in psys.particles:
                if (p.alive_state == 'ALIVE'):
                    points.append(p.location);
        name = obj.name + "_point_cloud"
        pointcloud = bpy.data.meshes.new(name)
        pointcloud.from_pydata(points, [], []) # Create a mesh with only verts
        obj_new = bpy.data.objects.new(name + "_point_cloud", pointcloud)
        bpy.context.collection.objects.link(obj_new)
        pointcloud.update()
        return {'FINISHED'}

__CLASSES__ = [
    HI_PHY_OT_ConvertParticlesToPointCloud
]

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


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