"""
Donut
Copyright (c) 2022-present NAVER Corp.
MIT License
"""
import numpy as np
from synthtiger import layers


class TextBox:
    def __init__(self, config):
        self.fill = config.get("fill", [1, 1])

    def generate(self, size, text, font):
        width, height = size

        word_layers, words = [], []
        fill = np.random.uniform(self.fill[0], self.fill[1])
        width = np.clip(width * fill, height, width)
        font = {**font, "size": int(height)}
        left, top = 0, 0

        for word in text:
            if word in "\r\n\t":
                continue

            word_layer = layers.TextLayer(word, **font)
            char_scale = height / word_layer.height
            word_layer.bbox = [left, top, *(word_layer.size * char_scale)]
            if word_layer.right > width:
                break

            word_layers.append(word_layer)
            words.append(word)
            left = word_layer.right

        text = "".join(words).strip()
        if len(word_layers) == 0 or len(text) == 0:
            return None, None

        text_layer = layers.Group(word_layers).merge()

        return text_layer, text
