#include <fly/SimpleIni.h>

#include <QApplication>
#include <QX11Info>
#include <QDesktopWidget>
#include <QColor>
#include <QPixmap>
#include <QImage>
#include <QPainter>
#include <QTimer>
#include <QSvgRenderer>

#include <QBackingStore>


#include <X11/Xlib.h>

#include <stdlib.h>
#include <limits.h>


#ifndef QDMCONF
#define QDMCONF "/etc/X11/fly-dm"
#endif

int main(int argc, char *argv[])
{
    QApplication  app( argc,argv );

    QString       colorStr, imageStr, modeStr;
    QColor        color;
    QPixmap       image;
    QDesktopWidget *d=app.desktop();

    d->setAttribute(Qt::WA_PaintOnScreen,true);

    if (argc < 2) fprintf(stderr,"fly-dmrootimage: No file specified\n");

    const char *tmp;
    CSimpleIniA ini(true,false,false);
    SI_Error rc = ini.LoadFile(argv[1]);
    if (rc<0)
    {
	fprintf(stderr,"Can't work with file %s\n",argv[1]);
	return 1;
    }

    char buf[PATH_MAX];

    char section[15]="Desktop0";
/*  if (XDisplayName(buf)) //get display name and extract display index
    {
	char *tmp=strrchr(buf,':');
	if (tmp && tmp[1]!='0')
	{
    	    char *tmp2=strrchr(buf,'.');
    	    if (tmp2>tmp) *tmp2='\0';
    	    strcpy(section+7,tmp+1);
	}
    }
*/ //TODO: there cab be several sections [Desktop?Screen?] 
   // so we could set separate bg for each of them if defined or 
   // use common from [Background Common] section

    QColor color1;
    *buf='\0';

    tmp = ini.GetValue(section,"Color1", "darkblue");
    strncpy(buf,tmp,sizeof(buf)-1); buf[sizeof(buf)-1]='\0';

    //if (*buf=='\"') { *buf=' '; buf[strlen(buf)-1]='\0'; } //remove quotes
    if (strchr(buf,',')) //color is r,g,b
    {
	int r,g,b;
	sscanf(buf,"%d,%d,%d",&r,&g,&b);
	color1=QColor(r,g,b);
    }
    else color1=QColor((const char *)buf); //else - color is string


    char mode[30]="Scaled";
    *buf='\0';

    tmp = ini.GetValue(section,"WallpaperMode", "Scaled");
    strncpy(buf,tmp,sizeof(buf)-1); buf[sizeof(buf)-1]='\0';

    //if (*buf=='\"') { *buf=' '; buf[strlen(buf)-1]='\0'; } //remove quotes
    if (*buf) { strncpy(mode,buf,sizeof(mode)-1); mode[sizeof(mode)-1]='\0'; }

    *buf='\0';

    if (!strcmp(mode,"NoWallpaper")) goto set_color;

    tmp = ini.GetValue(section,"Wallpaper", "");
    strncpy(buf,tmp,sizeof(buf)-1); buf[sizeof(buf)-1]='\0';

    //if (*buf=='\"') { *buf=' '; buf[strlen(buf)-1]='\0'; } //remove quotes 
    if (*buf)
    {
        QImage image;
        QString imagePath = QString::fromLocal8Bit(buf);
        if (*buf!='/') imagePath.prepend("/usr/share/wallpapers/");

        QRect    dr(0,0,d->width(),d->height());
        QPixmap  pm(d->width(),d->height());
        if (color1.isValid()) pm.fill(color1);
        QPainter p(&pm);

        if (imagePath.endsWith(".svg") || imagePath.endsWith(".svgz"))
        {
            QSvgRenderer svgr(imagePath);
            svgr.render(&p);
        }
        else
        {
            image.load(imagePath);
            if (image.isNull())
            {
                fprintf(stderr,"fly-dmrootimage: image file %s not found or unsupported\n",imagePath.toLocal8Bit().data());
                goto set_color;
            }

                 if (!strcmp(mode+1,"iled"))  p.drawTiledPixmap(dr,QPixmap::fromImage(image));
           else if (!strcmp(mode+1,"caled")) p.drawPixmap(dr,QPixmap::fromImage(image));
           else p.drawPixmap(d->width()/2 - image.width()/2, d->height()/2 - image.height()/2, QPixmap::fromImage(image)); //centered as default 
        }

        //QWindow * rootWindow = QWindow::fromWinId(QX11Info::appRootWindow());
        QWindow * rootWindow = d->windowHandle();
        rootWindow->resize(QSize(d->width(),d->height()));

        if (rootWindow && getenv("QT_XCB_NATIVE_PAINTING"))
        {
            fprintf(stderr,"QT_XCB_NATIVE_PAINTING is set, root window = %lu, rect = %d %d %d %d, root win %d %d\n", 
                            QX11Info::appRootWindow(), d->x(),d->y(),d->width(),d->height(), 
                            rootWindow->size().width(),rootWindow->size().height());

            QRect rect(d->x(),d->y(),d->width(),d->height());

            QBackingStore  backingStore(rootWindow);

            backingStore.resize(QSize(rect.width(),rect.height()));

            fprintf(stderr,"bs rect = %d %d\n",backingStore.size().width(),backingStore.size().height());

            backingStore.beginPaint(rect);

            QPaintDevice *paintDevice = backingStore.paintDevice();
            QPainter painter(paintDevice);

            painter.drawPixmap(rect,pm);


            backingStore.endPaint();
            backingStore.flush(QRegion(rect));
        }
        else
        {
            QPalette pal = d->palette();
            pal.setBrush(d->backgroundRole(),QBrush(pm));
            d->setPalette(pal);

            //d->repaint();
            XClearWindow( QX11Info::display(), d->winId() );
        }
        fprintf(stderr,"fly-dmrootimage: set image file %s\n",imagePath.toLocal8Bit().data());
    }
    else
    {
set_color:
      if (color1.isValid())
      {
        QPalette pal = d->palette();
        pal.setColor(d->backgroundRole(),color1);
        d->setPalette(pal);
        fprintf(stderr,"fly-dmrootimage: set color '%s'\n",color1.name().toLocal8Bit().data());

        //d->repaint();
        XClearWindow( QX11Info::display(), d->winId() );
      }
    }

    return 0;
}

