from abcforge.vendor.abctoolkit.utils import (
    extract_barline_and_bartext_dict,
    extract_barline_and_bartext_dict_rotated,
)


def rotate_abc(abc_lines: list):

    metadata_lines, prefix_dict, left_barline_dict, bar_text_dict, right_barline_dict = \
        extract_barline_and_bartext_dict(abc_lines)

    rotated_abc_lines = metadata_lines
    for i, line in enumerate(rotated_abc_lines):
        if not line.endswith('\n'):
            rotated_abc_lines[i] = line + '\n'

    line_0 = ''
    for symbol in prefix_dict.keys():
        part_patch = '[' + symbol + ']'
        part_patch += prefix_dict[symbol]
        part_patch += left_barline_dict[symbol][0]
        part_patch += bar_text_dict[symbol][0]
        part_patch += right_barline_dict[symbol][0]
        line_0 += part_patch
    line_0 += '\n'
    rotated_abc_lines.append(line_0)

    for i in range(1, len(bar_text_dict['V:1'])):
        line = ''
        for symbol in prefix_dict.keys():
            part_patch = '[' + symbol + ']'
            part_patch += bar_text_dict[symbol][i]
            part_patch += right_barline_dict[symbol][i]
            line += part_patch
        line += '\n'
        rotated_abc_lines.append(line)

    return rotated_abc_lines


def unrotate_abc(abc_lines: list):

    metadata_lines, prefix_dict, left_barline_dict, bar_text_dict, right_barline_dict = \
        extract_barline_and_bartext_dict_rotated(abc_lines)

    unrotated_abc_lines = metadata_lines
    for i, line in enumerate(unrotated_abc_lines):
        if not line.endswith('\n'):
            unrotated_abc_lines[i] = line + '\n'

    for symbol in prefix_dict.keys():
        unrotated_abc_lines.append(symbol + '\n')
        bar_index = 0
        line_len = 0
        line = prefix_dict[symbol] + left_barline_dict[symbol][0] + ' '
        while bar_index < len(bar_text_dict[symbol]):
            bar = bar_text_dict[symbol][bar_index] + ' ' + \
                  right_barline_dict[symbol][bar_index] + ' '
            if line_len == 0 or line_len + len(bar) <= 100:
                line += bar
                line_len += len(bar)
                bar_index += 1
            else:
                line += '\n'
                unrotated_abc_lines.append(line)
                line = ' '
                line_len = 0
        if line.strip() != '':
            line += '\n'
            unrotated_abc_lines.append(line)

    return unrotated_abc_lines
