import os
import math
def get_plugin_ebv():
    file_name = 'plugin.ebv'
    file_path = f"{pynebv.plugin.temp_dir}/{file_name}"
    # Create file if file_path does not exists
    if not os.path.exists(file_path):
        f = open(file_path, 'w')
        f.write("#EBV\nunit 1\n")
        f.close()
    return file_path

class BoxCreate(pynebv.Plugin):
    location = 'screen/context_menu'
    contact = 'ncs'
    label = 'Create Box'
    def __init__(self):
        if not hasattr(pynebv, 'fig_index'):
            pynebv.fig_index = 0
    def exec(self, context):
        if hasattr(pynebv, 'error_mode'):
            raise RuntimeError('Error mode is already set')
        print(context)
        if not 'area' in context:
            return
        x1 = context["area"][0]
        y1 = context["area"][1]
        x2 = context["area"][2]
        y2 = context["area"][3]
        # Add a box to file
        file_path = get_plugin_ebv()
        f = open(file_path, 'a')
        f.write("layno %d\n" % (pynebv.fig_index))
        pynebv.fig_index += 1
        f.write("rect %f,%f,%f,%f\n" % (x1, y1, x2 - x1, y2 - y1))
        f.close()
        # Read and display the file
        if len(pynebv.file.items(os.path.basename(file_path))) == 0:
            pynebv.file.open(file_path)
        pynebv.file.reload(True)

class ArrowCreate(pynebv.Plugin):
    location = 'screen/context_menu'
    contact = 'ncs'
    label = 'Create Arrow'
    def __init__(self):
        if not hasattr(pynebv, 'fig_index'):
            pynebv.fig_index = 0
    def exec(self, context):
        if hasattr(pynebv, 'error_mode'):
            raise RuntimeError('Error mode is already set')
        print(context)
        if not 'start_end' in context:
            return
        sx = context["start_end"][0]
        sy = context["start_end"][1]
        ex = context["start_end"][2]
        ey = context["start_end"][3]
        points = self.calculate_arrow_points(sx, sy, ex, ey)
        # Add an arrow to file
        file_path = get_plugin_ebv()
        f = open(file_path, 'a')
        f.write("layno %d\n" % (pynebv.fig_index))
        pynebv.fig_index += 1
        f.write("polygon\n")
        for x, y in points:
            f.write("xy %f,%f\n" % (x, y))
        f.write("end\n")
        f.close()
        # Read and display the file
        if len(pynebv.file.items(os.path.basename(file_path))) == 0:
            pynebv.file.open(file_path)
        pynebv.file.reload(True)
    def calculate_arrow_points(self, sx, sy, ex, ey):
        length = math.hypot(ex - sx, ey - sy)
        arrow_points = [
            (0, 0),
            (-0.2, 0.2),
            (-0.1, 0.2),
            (-0.1, 1),
            (0.1, 1),
            (0.1, 0.2),
            (0.2, 0.2),
        ]
        
        # Calculate arrow angle
        angle = math.atan2(ey - sy, ex - sx)
        cos = math.cos(angle)
        sin = math.sin(angle)

        # Calculation with arrow reference position set to (sx, sy)
        points = []
        for x, y in arrow_points:
            # Adjust size
            x *= length
            y *= length
            # Rotate and move
            points.append((
                ex + x * sin - y * cos,
                ey - x * cos - y * sin
            ))

        return points

class CreatePoint(pynebv.Plugin):
    location = 'screen/context_menu'
    contact = 'ncs'
    label = 'Create Point'
    def __init__(self):
        if not hasattr(pynebv, 'fig_index'):
            pynebv.fig_index = 0
    def exec(self, context):
        if hasattr(pynebv, 'error_mode'):
            raise RuntimeError('Error mode is already set')
        x = context['point'][0]
        y = context['point'][1] 
        # Add X to file
        file_path = get_plugin_ebv()
        f = open(file_path, 'a')
        f.write("layno %d\n" % (pynebv.fig_index))
        pynebv.fig_index += 1
        f.write("polygon\n")
        area = pynebv.screen.get_area()
        width = area[2] - area[0]
        height = area[3] - area[1]
        min_size = width if width < height else height
        unit = min_size / 100
        f.write("xy %f,%f\n" % (x, y + 1 * unit))
        f.write("xy %f,%f\n" % (x + 9 * unit, y + 11 * unit))
        f.write("xy %f,%f\n" % (x + 11 * unit, y + 9 * unit))
        f.write("xy %f,%f\n" % (x + 1 * unit, y ))
        f.write("xy %f,%f\n" % (x + 11 * unit, y - 9 * unit))
        f.write("xy %f,%f\n" % (x + 9 * unit, y - 11 * unit))
        f.write("xy %f,%f\n" % (x, y - 1 * unit))
        f.write("xy %f,%f\n" % (x - 9 * unit, y - 11 * unit))
        f.write("xy %f,%f\n" % (x - 11 * unit, y - 9 * unit))
        f.write("xy %f,%f\n" % (x - 1 * unit, y))
        f.write("xy %f,%f\n" % (x - 11 * unit, y + 9 * unit))
        f.write("xy %f,%f\n" % (x - 9 * unit, y + 11 * unit))
        f.write("end\n")
        f.close()
        pynebv.file.reload(True)

