from enum import Enum

class Machine(Enum):
    LASER = 1
    THREEAXIS = 2

class Gcode:
    def __init__(self, file, mm_per_px, speed, machine, max_s=0, safe_z=0, work_z=0):
        self.file = file
        self.mm_per_px = mm_per_px
        self.speed = speed
        self.machine = machine
        self.max_s = max_s
        self.safe_z = safe_z
        self.work_z = work_z
        self.output = None
        self.init_file()

    def init_file(self):
        # self.output = open(f"{self.file}.gcode", "w")
        self.output = ""
        self.output += ("G21   ;Unit to mm\n")
        self.output += ("G90   ;Absolute positioning\n\n")
        self.output += (f"F{self.speed}\n")
        if self.machine == Machine.LASER:
            self.output += (f"S{self.max_s}\n")
        self.output += ("M3\n\n")


    def draw_line(self, x1, y1, x2, y2):
        self.go_to(x1, y1)
        self.write_to(x2, y2)

    def go_to(self, x, y):
        x_mm = x * self.mm_per_px
        y_mm = y * self.mm_per_px

        if self.machine == Machine.LASER:
            self.output+=(f"G0 X{x_mm} Y{y_mm}\n")
        elif self.machine == Machine.THREEAXIS:
            self.output+=(f"G0 Z{self.safe_z}\n")
            self.output+=(f"G0 X{x_mm} Y{y_mm} Z{self.safe_z}\n")

    def write_to(self, x, y):
        x_mm = x * self.mm_per_px
        y_mm = y * self.mm_per_px

        if self.machine == Machine.LASER:
            self.output += (f"G1 X{x_mm} Y{y_mm}\n")
        elif self.machine == Machine.THREEAXIS:
            self.output += (f"G0 Z{self.work_z}\n")
            self.output += (f"G1 X{x_mm} Y{y_mm} Z{self.work_z}\n")

    def refill(self, x, y, depth, dip_number):
        self.output += (";#################\n")

        if self.machine == Machine.THREEAXIS:
            self.go_to(x, y)
            for _ in range(dip_number):
                self.output += (f"G1 Z{depth}\n")
                self.output += (f"G0 Z{self.safe_z}\n")
        elif self.machine == Machine.LASER:
            self.go_to(x, y)
            self.set_pause()

    def set_pause(self):
        self.output += ("M0\n")

    def end_gcode(self):
        if self.machine == Machine.THREEAXIS:
            self.go_to(0, 0)

        self.output += ("M5\n")
        # self.output.close()

    def new_file(self, new_file_name):
        self.end_gcode()
        self.file = new_file_name
        self.init_file()
