//
// Created by 423A35C7 on 2023-11-12.
//
// 11:47
// 14:55

#include <algorithm>
#include <iostream>
#include <string>
#include "bitree.cpp"

#define move_and_output(x, y, str) printf("\033[s\033[%d;%dH%s\033u", x, y, str)
// 移动并输出到指定位置
#define moveto(x, y) printf("\033[s\033[%d;%dH", x, y)
// 移动到指定位置
#define movedown(x) printf("\033[%dB", (x))
// 向下移动指定行
#define save_cursor() printf("\033[s")
// 保存光标位置
#define restore_cursor() printf("\033[u")
// 恢复光标位置
#define clear_char(num)           \
for (int i = 0; i < num; i++) \
printf(" ")
// 清空指定位置的字符
#define clear_screen() printf("\033[2J")

// class ViewBox {
//     Node *left_node;
//     int x, y;
//     int width;
//     int height;
//     struct Size {
//         int width;
//         int height;
//     };
//     Size calculate_size(Node *left_node) {
//         Size size {left_node->text.length(), 1};
//         if (left_node->left) {
//             Size increment;
//             increment = calculate_size(left_node->left);
//
//         }
//     }
// };

enum LINE {NONE, HORIZONTAL, VERTICAL};

int get_length(Node *node) {
    // 2是_和空格的长度
    return std::to_string(node->num).length() + 2 + node->text.length();
}

void print(Node *node, int x, int y, LINE line_type) {
    // 移动到指定位置
    moveto(2 * x, y);
    // 保存当前光标位置
    save_cursor();
    // 如果line_type为VERTICAL,则输出“|”
    if (line_type == VERTICAL) {
        std::cout << "|";
    }
    // 恢复光标位置
    restore_cursor();
    // 向下移动1个单位
    movedown(1);
    // 如果line_type为HORIZONTAL,则输出“——”
    if (line_type == HORIZONTAL) {
        std::cout << "——";
    }
    // 输出node的num和text
    std::cout << node->num << "_" << node->text << " ";
}

int output(Node *left_node, int x, int y) {
    int width = 0;
    if (left_node == nullptr) return width;
    // 打印左节点
    print(left_node, x, y, VERTICAL);
    // 计算宽度
    width += std::max(get_length(left_node), output(left_node->left, x + 1, y + width));
    // 遍历右节点
    for (Node *temp = left_node; temp->right && !temp->if_right_chain; temp = temp->right) {
        // 打印右节点
        print(temp->right, x, y + width, HORIZONTAL);
        // 计算宽度
        // 2是——的长度
        width += std::max(2 + get_length(temp->right), output(temp->right->left, x + 1, y + width));
        // width += temp->right->text.length();
    }
    return width;
    // if (left_node->left == nullptr) {
    //     return width;
    // }
    // depth += 1;
    // return std::max(width, output(left_node->left,  depth));
}