#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/container/XIndexAccess.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/text/XTextDocument.hpp>
#include <com/sun/star/text/XTextGraphicObjectsSupplier.hpp>
#include <com/sun/star/drawing/XShape.hpp>


using namespace com::sun::star::text;
using namespace com::sun::star::awt;
using namespace com::sun::star::drawing;
using namespace com::sun::star::container;

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("writer8");
        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.odt", "_blank", 0, props);

        //Получаем объект документа
        Reference<XTextDocument> xDoc(xComponent, UNO_QUERY_THROW);
        //Получаем объект текста
        Reference<XText> xText = xDoc->getText();
        //Получаем объект XMultiServiceFactory для создания TextGraphicObject
        Reference<XMultiServiceFactory> xServiceFactory(xDoc, UNO_QUERY_THROW);
        //Получаем объект XTextContent для вставки в метод insertTextContent() интерфейса XText. И создаем экземпляр объекта TextGraphicObject
        Reference<XTextContent> xTextContent(xServiceFactory->createInstance("com.sun.star.text.TextGraphicObject"), UNO_QUERY_THROW);
        //Получаем объект XShape для доступа к размеру формы
        Reference<XShape> xShape(xTextContent, UNO_QUERY_THROW);
        //Получаем доступ к свойствам 
        Reference<XPropertySet>xProps(xShape, UNO_QUERY_THROW);
        OUString imagePath = "file:///C:/test/test.jpg";
        xProps->setPropertyValue("GraphicURL", Any(imagePath));
        //Вставляем изображение
        xText->insertTextContent(xText->getEnd(), xTextContent, true);
        Size size;
        size.Width = 10000;
        size.Height = 10000;
        xShape->setSize(size);


        Reference<XShape> xShapeEllipse(xServiceFactory->createInstance("com.sun.star.drawing.EllipseShape"), UNO_QUERY_THROW);
        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)));
        Reference<XTextContent> xTextContentEllipse(xShapeEllipse, UNO_QUERY_THROW);
        xText->insertTextContent(xText->getEnd(), xTextContentEllipse, false);


        // получаем интерфейс 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.odt");

        // сохраняем документ
        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;
}
