#include <stdio.h>
#include <sal/main.h>
#include <cppuhelper/bootstrap.hxx>
#include <com/sun/star/bridge/XUnoUrlResolver.hpp>
#include <com/sun/star/frame/Desktop.hpp>
#include <com/sun/star/frame/XComponentLoader.hpp>
#include <com/sun/star/lang/XMultiComponentFactory.hpp>
#include <com/sun/star/frame/XStorable.hpp>
#include <com/sun/star/awt/XMessageBoxFactory.hpp>
#include <com/sun/star/awt/MessageBoxButtons.hpp>
#include <com/sun/star/awt/MessageBoxType.hpp>
#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/sheet/XSpreadsheetDocument.hpp>
#include <com/sun/star/container/XIndexAccess.hpp>
#include <com/sun/star/container/XNamed.hpp>


using namespace com::sun::star::container;
using namespace com::sun::star::sheet;
using namespace com::sun::star::awt;
using namespace com::sun::star::beans;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::frame;
using ::rtl::OUString;
using ::rtl::OUStringToOString;

SAL_IMPLEMENT_MAIN_WITH_ARGS(argc, argv)
{
    try
    {
        //  получаем контекст компонентов офиса
        Reference< XComponentContext > xContext(::cppu::bootstrap());
        if (!xContext.is())
        {
            fprintf(stderr, "no component context!\n");
            return 1;
        }

        // получаем сервис-менеджер офиса
        Reference<XMultiComponentFactory> xServiceManager(
            xContext->getServiceManager());
        if (!xServiceManager.is())
        {
            fprintf(stderr, "no service manager!\n");
            return 1;
        }

        //Создание объекта xToolkit
        Reference<XToolkit> xToolkit(
            xServiceManager->createInstanceWithContext(
                "com.sun.star.awt.Toolkit", nullptr),
            UNO_QUERY);


        // получаем экземпляр сервиса UNO Desktop
        // получаем интерфейс XComponentLoader
        Reference <XDesktop2> xComponentLoader = Desktop::create(xContext);

        // создаем новый документ
        Sequence<PropertyValue> props(1);
        PropertyValue prop;
        prop.Name = "FilterName";
        prop.Value <<= OUString("calc8");
        props[0] = prop;
        Reference<XComponent> xComponent(xComponentLoader->loadComponentFromURL(
            OUString("file:///C:/test/document.ods"), "_blank", 0, props));
        if (!xComponent.is())
        {
            fprintf(stderr, "creating writer document failed!\n");
            return 1;
        }


        // получаем интерфейс XStorable для текущего документа
        Reference< XStorable > xStorable(xComponent, UNO_QUERY);
        if (!xStorable.is())
        {
            fprintf(stderr, "getting XStorable interface failed!\n");
            return 1;
        }


        // задаем URL для сохранения документа
        OUString saveUrl("file:///C:/test/document.ods");

        // Получаем интерфейс XWindowPeer
        Reference<XWindowPeer> xWP(xContext, UNO_QUERY);
        // Получаем интерфейс XMessageBoxFactory для создания диалогового окна
        Reference<XMessageBoxFactory> xMB(xToolkit, UNO_QUERY);
        // Получаем интерфейс XSpreadsheetDocument для работы с таблицами
        Reference<XSpreadsheetDocument> xDoc(xComponent, UNO_QUERY);
        // Получаем интерфейс XSpreadsheets для работы с листами
        Reference<XSpreadsheets> xSheets = xDoc->getSheets();
        // Получаем интерфейс XIndexAccess для получения количества листов
        Reference<XIndexAccess> xSheetIA(xSheets, UNO_QUERY);
        // Получаем количество листов
        sal_Int32 sheetCount = xSheetIA->getCount();

        rtl::OUString sheetCountString = rtl::OUString::number(sheetCount);
        rtl::OUString numberOfSheets = "Number of sheets: " + sheetCountString;
        // Создаем диалоговое окно с сообщением
        Reference<XMessageBox> xMessageBox = xMB->createMessageBox(
            xWP, com::sun::star::awt::MessageBoxType::MessageBoxType_MESSAGEBOX, MessageBoxButtons::BUTTONS_OK,
            "Title", numberOfSheets);
        // Выполняем диалоговое окно
        xMessageBox->execute();


        for (sal_Int32 i = 0; i < xSheetIA->getCount(); ++i) {
            Reference<XInterface> xSheetInterface(xSheetIA->getByIndex(i), UNO_QUERY);
            if (xSheetInterface.is()) {
                Reference<XNamed> xSheetName(xSheetInterface, UNO_QUERY);
                OUString sheetName = xSheetName->getName();
                Reference<XMessageBox> xMessageBox = xMB->createMessageBox(
                    xWP, com::sun::star::awt::MessageBoxType::MessageBoxType_MESSAGEBOX, MessageBoxButtons::BUTTONS_OK,
                    "Title", sheetName);
                xMessageBox->execute();
            }
        }


        

        // Сохранение документа
        xStorable->storeAsURL(saveUrl, props);


        // Закрытие документа
        //xComponent->dispose();
    }
    catch (::cppu::BootstrapException& e)
    {
        fprintf(stderr, "caught BootstrapException: %s\n",
            OUStringToOString(e.getMessage(), RTL_TEXTENCODING_ASCII_US).getStr());
        return 1;
    }
    catch (Exception& e)
    {
        fprintf(stderr, "caught UNO exception: %s\n",
            OUStringToOString(e.Message, RTL_TEXTENCODING_ASCII_US).getStr());
        return 1;
    }

    return 0;
}