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


class sketch_from_svg:

    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):
        if not string:
            return (0, 0, 0)

        if string.startswith('#'):
            string = string[1:]

        if len(string) == 3:
            string = ''.join([c*2 for c in string])

        r = int(string[0:2], 16)/255
        g = int(string[2:4], 16)/255
        b = int(string[4:6], 16)/255

        return r, g, b

    def load_svg(self):
        print('loading data')
        paths, attributes, svg_att = svg2paths2(self.path)

        h = svg_att["height"].replace("px", "")
        w = svg_att["width"].replace("px", "")

        self.height = int(float(h))
        self.width = int(float(w))

        res = []

        for i in tqdm(attributes):
            path = parse_path(i['d'])

            co = i.get('fill', '#000000')
            col = self.hex_to_rgb(co)

            n = 100  # smoothness

            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(n+1))
            ]

            res.append((pts, col))

        print('svg data loaded')
        return res

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

    def draw(self):
        tu.tracer(0, 0)  # FAST DRAWING

        coordinates = self.load_svg()
        self.pen = tu.Turtle()
        self.pen.speed(0)

        for path, col in coordinates:
            self.pen.color(col)
            self.pen.begin_fill()

            first = True
            for x, y in path:
                y *= -1
                if first:
                    self.move_to(x, y)
                    first = False
                else:
                    self.pen.goto(x, y)

            self.pen.end_fill()

        tu.update()
        tu.done()


# Run
pen = sketch_from_svg('hanumanji.svg', scale=70)
pen.draw()