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

#include <stdio.h>
#include <string.h>


int write_cells()
{
    DocumentHandle doc = doc_create();
    WorkbookHandle wb = doc_get_workbook(doc);
    WorksheetHandle ws = wb_add_worksheet(wb, "Write cells");
    if (!ws)
    {
        printf("%s\n", run_msg());
        doc_release(doc);
        return 0;
    }

    int row = 2, col = 2;

    // Set title
    ws_set_text(ws, row, col, "Type");
    ws_set_text(ws, row, col + 1, "Value");

    // Set type discription
    ws_set_text(ws, row + 1, col, "Number");
    ws_set_text(ws, row + 2, col, "String");
    ws_set_text(ws, row + 3, col, "Boolean");
    ws_set_text(ws, row + 4, col, "Datetime");
    ws_set_text(ws, row + 5, col, "Error");

    // Set data type and value
    ws_set_num(ws, row + 1, col + 1, 123.456);
    ws_set_text(ws, row + 2, col + 1, "This is a string.");
    ws_set_boolean(ws, row + 3, col + 1, 1);
    double dt = encode_date(2026, 2, 7);
    ws_set_datetime(ws, row + 4, col + 1, dt);
    dt = ws_get_datetime(ws, row + 4, col + 1);
    ws_set_error(ws, row + 5, col + 1, ERRCODE_DIV_0);

    // Save to file
    int result = 1;
    if (!doc_save(doc, target_file("read_and_write_cells.xlsx")))
    {
        printf("%s\n", run_msg());
        result = 0;
    }

    doc_release(doc);
    return result;
}

int read_cells()
{
    DocumentHandle doc = doc_load(target_file("read_and_write_cells.xlsx"));
    if (!doc)
    {
        printf("%s\n", "Cannot open the file named \"read_and_write_cells_cells.xlsx\".");
        return 0;
    }

    WorkbookHandle wb = doc_get_workbook(doc);
    int num = wb_sheet_count(wb);
    int result = 0;
    for (int i = 0; i < num; ++i)
    {
        const char* name = wb_sheet_name(wb, i);
        if (!strcmp(name, "Write cells"))
        {
            WorksheetHandle w_ws = wb_get_sheet(wb, i);
            WorksheetHandle r_ws = wb_add_worksheet(wb, "Read from \"Write cells\"");

            // Read data
            int row = 3, col = 3;
            double v = ws_get_num(w_ws, row, col);
            const char* s = ws_get_text(w_ws, row + 1, col);
            int b = ws_get_boolean(w_ws, row + 2, col);
            double dt = ws_get_datetime(w_ws, row + 3, col);
            int e = ws_get_error(w_ws, row + 4, col);

            // Write data
            ws_set_num(r_ws, row, col, v);
            ws_set_text(r_ws, row + 1, col, s);
            ws_set_boolean(r_ws, row + 2, col, b);
            ws_set_datetime(r_ws, row + 3, col, dt);
            ws_set_error(r_ws, row + 4, col, e);

            // Save again
            result = 1;
            if (!doc_save(doc, NULL))
            {
                printf("%s\n", run_msg());
                result = 0;
            }
        }
    }

    doc_release(doc);
    return result;
}

