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

#include <iostream>
#include <string_view>


using namespace oo;

bool write_cells()
{
    Document* doc = create_document();

    Workbook* wb = doc->get_workbook();
    Worksheet* ws = wb->add_worksheet("Write cells");
    if (!ws)
    {
        std::cout << run_msg() << std::endl;
        doc->release();
        return false;
    }

    int row = 2, col = 2;

    // Set title
    ws->set_text(row, col, "Type");
    ws->set_text(row, col + 1, "Value");

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

    // Set data type and value
    ws->set_num(row + 1, col + 1, 123.456);
    ws->set_text(row + 2, col + 1, "This is a string.");
    ws->set_boolean(row + 3, col + 1, true);
    double dt = encode_date(2026, 2, 7);
    ws->set_datetime(row + 4, col + 1, dt);
    dt = ws->get_datetime(row + 4, col + 1);
    ws->set_error(row + 5, col + 1, ERRCODE_DIV_0);

    // Save to file
    bool result = true;
    auto path = target_file("read_and_write_cells.xlsx");
    if (!doc->save(path.string().c_str()))
    {
        std::cout << run_msg() << std::endl;
        result = false;
    }

    doc->release();
    return result;
}

bool read_cells()
{
    auto path = target_file("read_and_write_cells.xlsx");
    Document* doc = load_document(path.string().c_str());
    if (!doc)
    {
        std::cout << "Can not open the file named \"read_and_write_cells_cells.xlsx\"." << std::endl;
        return false;
    }

    Workbook* wb = doc->get_workbook();
    int num = wb->sheet_count();
    bool result = false;
    for (int i = 0; i < num; ++i)
    {
        std::string_view name = wb->sheet_name(i);
        if (name == "Write cells")
        {
            Worksheet* w_ws = wb->get_sheet(i);
            Worksheet* r_ws = wb->add_worksheet("Read from \"Write cells\"");

            // Read data
            int row = 3, col = 3;
            double v = w_ws->get_num(row, col);
            const char* s = w_ws->get_text(row + 1, col);
            bool b = w_ws->get_boolean(row + 2, col);
            double dt = w_ws->get_datetime(row + 3, col);
            ErrorCodeEnum e = w_ws->get_error(row + 4, col);

            // Write data
            r_ws->set_num(row, col, v);
            r_ws->set_text(row + 1, col, s);
            r_ws->set_boolean(row + 2, col, b);
            r_ws->set_datetime(row + 3, col, dt);
            r_ws->set_error(row + 4, col, e);

            // Save again
            result = true;
            if (!doc->save())
            {
                std::cout << run_msg() << std::endl;
                result = false;
            }
        }
    }

    doc->release();
    return result;
}

