#include <stdio.h>
#include <sal/main.h>
#include <cppuhelper/bootstrap.hxx>
#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/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/frame/XStorable.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/sheet/XSpreadsheetDocument.hpp>
#include <com/sun/star/container/XIndexAccess.hpp>
#include <com/sun/star/drawing/XDrawPagesSupplier.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>



using namespace com::sun::star::awt;
using namespace com::sun::star::drawing;
using namespace com::sun::star::container;
using namespace com::sun::star::sheet;
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;
        }

        // получаем экземпляр сервиса UNO Desktop
        // получаем интерфейс XComponentLoader
        Reference<XComponentLoader> xLoader(xContext->getServiceManager()->createInstanceWithContext(
            "com.sun.star.frame.Desktop", xContext), UNO_QUERY);


        // создаем новый документ
        Sequence<PropertyValue> props(2);
        PropertyValue prop[2];
        prop[0].Name = "FliterName";
        prop[0].Value <<= OUString("calc8");
        prop[1].Name = "Overwrite";
        prop[1].Value <<= Any(true);
        props[0] = prop[0];
        props[1] = prop[1];
        Reference<XInterface> xComponent = xLoader->loadComponentFromURL(
            "file:///C:/test/document.ods", "_blank", 0, props);

        //Получаем объект документа
        Reference<XSpreadsheetDocument> xDoc(xComponent, UNO_QUERY_THROW);
        //Получаем объект XDrawPagesSupplier для обеспечения доступа к объекту рисунка
        Reference<XDrawPagesSupplier>xSheetSupplier(xDoc, UNO_QUERY_THROW);
        //Получаем объект XDrawPages
        Reference<XDrawPages> xDP = xSheetSupplier->getDrawPages();
        Reference<XIndexAccess> xIA(xDP, UNO_QUERY_THROW);
        //Получаем объект коллекции форм
        Reference<XShapes> xShapes(xIA->getByIndex(0), UNO_QUERY_THROW);
        Reference<XMultiServiceFactory> xServiceFactory(xDoc, UNO_QUERY_THROW);
        //Создаем объект GraphicObjectShape через XMultiServiceFactory
        Reference<XShape> xShape(xServiceFactory->createInstance("com.sun.star.drawing.GraphicObjectShape"), UNO_QUERY_THROW);
        //Получаем доступ к свойствам xShape
        Reference<XPropertySet> xProps(xShape, UNO_QUERY_THROW);
        //Путь к картинке
        OUString path_qr_img = "file:///C:/test/test.jpg";
        //Устанавливаем размер и позицию изображения
        Size size;
        Point position;
        size.Width = 10000;
        size.Height = 10000;
        position.X = 0.9 * (10000 - size.Width);
        position.Y = 0.5 * (15000 - size.Width);
        xShape->setSize(size);
        xShape->setPosition(position);
        xProps->setPropertyValue("GraphicURL", Any(path_qr_img));
        //Добавляем изображение с установленными параметрами
        xShapes->add(xShape);


        //Создаем объект EllipseShape через XMultiServiceFactory
        Reference<XShape> xShapeEllipse(xServiceFactory->createInstance("com.sun.star.drawing.EllipseShape"), UNO_QUERY_THROW);
        //Получаем доступ к свойствам xShapeEllipse
        Reference<XPropertySet> xPropsEllipse(xShapeEllipse, UNO_QUERY_THROW);
        //Устанавливаем размер и позицию эллипса
        Size sizeEllipse;
        Point positionEllipse;
        sizeEllipse.Width = 10000;
        sizeEllipse.Height = 10000;
        positionEllipse.X = 0.9 * (30000 - size.Width);
        positionEllipse.Y = 0.5 * (15000 - size.Width);
        xShapeEllipse->setSize(sizeEllipse);
        xShapeEllipse->setPosition(positionEllipse);
        //Устанавилвает красный цвет эллипса 
        xPropsEllipse->setPropertyValue("FillColor", Any(long(0xFF0000)));
        //Добавляем эллипс с установленными параметрами 
        xShapes->add(xShapeEllipse);

        // получаем интерфейс 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");

        // сохраняем документ
        xStorable->storeAsURL(saveUrl, props);

        // закрываем документ

       //xDoc->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;
}
