
#include "../include/create_document.h"
#include "../include/file_path.h"
#include <oosxl.h>

#include <stdio.h>


int create_new_document()
{
    DocumentHandle doc = doc_create();
    WorkbookHandle wb = doc_get_workbook(doc);
    wb_add_worksheet(wb, NULL);

    if (!doc_save(doc, target_file("blank.xlsx")))
    {
        printf("%s\n", run_msg());
        return -1;
    }

    doc_release(doc);
    return 0;
}

void create_example_document()
{
    // Step 1: create a empty document
    DocumentHandle doc = doc_create();
    if (!doc)
    {
        printf("Error creating document: %s\n", run_msg());
        return;
    }

    // Step 2: There is only one unique workbook in a document
    WorkbookHandle wb = doc_get_workbook(doc);

    // Step 3: At least one worksheet must be added to a empty document
    WorksheetHandle ws = wb_add_worksheet(wb, NULL);

    // Now, let's start adding data to the worksheet

    int row = 3, col = 3;

    // Set titles
    const char* titles[] = {"Item", "Units", "Unit Cost", "Total"};
    for (int i = 0; i < sizeof(titles) / sizeof(char*); ++i)
        ws_set_text(ws, row, row + i, titles[i]);

    // Set the first column
    const char* column1[] = {"Baby doll", "Kite", "Toy guitar"};
    for (int i = 0; i < 3; ++i)
        ws_set_text(ws, row + i, col, column1[i]);

    // Set the second column
    int column2[] = {95, 60, 75};
    for (int i = 0; i < 3; ++i)
        ws_set_num(ws, row + i, col + 1, column2[i]);

    // Set the third column
    double column3[] = {1.99, 2.99, 6.99};
    for (int i = 0; i < 3; ++i)
        ws_set_num(ws, row + i, col + 2, column3[i]);

    // Set the fourth column
    ws_set_formula(ws, row, col + 3, "=D3*E3");
    ws_set_formula(ws, row + 1, col + 3, "=D4*E4");
    ws_set_formula(ws, row + 2, col + 3, "=D5*E5");

    // Merge cell(6,2) - cell(6,4)
    ws_merge(ws, row + 3, col, row + 3, col + 2);
    ws_set_text(ws, row + 3, col, "Total");

    // Set total
    ws_set_formula(ws, row + 3, col + 3, "=SUM(F3:F5)");

    // Set style
    StyleHandle fmt = wb_get_named_style(wb, "normal");
    style_set_border(fmt, BORDERINDEX_EDGE, BORDER_THICK);
    style_set_border(fmt, BORDERINDEX_INSIDE, BORDER_THIN);
    ws_set_range_style(ws, row, col, row + 3, col + 3, fmt);
    style_release(fmt);

    // Save to example.xlsx
    if (!doc_save(doc, target_file("example.xlsx")))
        printf("Error saving file: %s\n", run_msg());

    doc_release(doc);
}
