import turtle as tu
from svgpathtools import svg2paths2
from svg.path import parse_path
from tqdm import tqdm

class HanumanSketch:
    def __init__(self, path, scale=30, x_offset=350, y_offset=350):
        self.path = path
        self.x_offset = x_offset
        self.y_offset = y_offset
        self.scale = scale

    def hex_to_rgb(self, string):
        strlen = len(string)
        if string.startswith('#'):
            if strlen == 7:
                r, g, b = string[1:3], string[3:5], string[5:7]
            elif strlen == 4:
                r, g, b = string[1:2]*2, string[2:3]*2, string[3:4]*2
            elif strlen == 3:
                r, g, b = string[0:1]*2, string[1:2]*2, string[2:3]*2
            else:
                r, g, b = string[0:2], string[2:4], string[4:6]
            return int(r, 16)/255, int(g, 16)/255, int(b, 16)/255

    def load_svg(self):
        print('Loading SVG data...')
        paths, attributes, svg_att = svg2paths2(self.path)
        h, w = svg_att["height"], svg_att['width']
        self.height = int(h[:h.find('.')])
        self.width = int(w[:w.find('.')])
        res = []
        for i in tqdm(attributes):
            path = parse_path(i['d'])
            col = i['fill']
            col_rgb = self.hex_to_rgb(col)
            n = len(list(path)) + 2
            pts = [((int((p.real/self.width)*self.scale))-self.x_offset,
                     (int((p.imag/self.height)*self.scale))-self.y_offset)
                   for p in (path.point(i/n) for i in range(0, n+1))]
            res.append((pts, col_rgb))
        print('SVG data loaded.')
        return res

    def move_to(self, x, y):
        tu.up()
        tu.goto(x, y)
        tu.down()

    def draw(self, retain=True):
        coordinates = self.load_svg()
        tu.speed(0)
        for path_col in coordinates:
            path, col = path_col[0], path_col[1]
            tu.color(col)
            tu.begin_fill()
            f = 1
            for coord in path:
                x, y = coord
                y *= -1
                if f:
                    self.move_to(x, y)
                    f = 0
                else:
                    tu.goto(x, y)
            tu.end_fill()
        if retain:
            tu.done()

# Usage
hanuman_image_path = 'path/to/hanuman.svg'  # Replace with your SVG image path
hanuman_sketch = HanumanSketch(hanuman_image_path, scale=70)
hanuman_sketch.draw()
