#include "imagegallery.h"
#include <QPixmap>
#include <QImageReader>
#include <QFileInfo>
ImageGallery::ImageGallery(QWidget *parent) : QWidget(parent), currentColumnCount(1)
{
    scrollArea = new QScrollArea(this);
    scrollWidget = new QWidget(scrollArea);
    gridLayout = new QGridLayout(scrollWidget);

    scrollArea->setWidgetResizable(true);
    scrollArea->setWidget(scrollWidget);

    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(scrollArea);
    setLayout(mainLayout);
}

void ImageGallery::addImage(const QString &imagePath)
{
    QLabel *imageLabel = new QLabel(scrollWidget);
    QPixmap pixmap(imagePath);
    imageLabel->setPixmap(pixmap.scaledToWidth(200, Qt::SmoothTransformation));
    imageLabel->setAlignment(Qt::AlignCenter);


    int row = gridLayout->count() / currentColumnCount;
    int column = gridLayout->count() % currentColumnCount;

    gridLayout->addWidget(imageLabel, row, column);
}
void ImageGallery::addImagesFromDirectory(QDir &directory){
    QStringList filters;
    const QList<QByteArray> supportedFormats = QImageReader::supportedImageFormats();

    for(const QByteArray &format : supportedFormats){
        filters.append("*." + QString(format).toLower());
    }

    directory.setNameFilters(filters);
    directory.setFilter(QDir::Files | QDir::Readable);
    directory.setSorting(QDir::Name);

    const QFileInfoList fileList = directory.entryInfoList();
    for(const QFileInfo &fileInfo : fileList) {
        addImage(fileInfo.absoluteFilePath());
    }
}
void ImageGallery::setColumns(int columns)
{
    if (columns < 1) {
        columns = 1;  // Minimalna liczba kolumn to 1
    }

    currentColumnCount = columns;

    // Usuń wszystkie obrazy z layoutu
    QLayoutItem *item;
    while ((item = gridLayout->takeAt(0))) {
        delete item->widget();
        delete item;
    }

    // Dodaj obrazy ponownie z nową liczbą kolumn
    QList<QLabel*> labels = scrollWidget->findChildren<QLabel*>();
    for (int i = 0; i < labels.size(); ++i) {
        int row = i / currentColumnCount;
        int column = i % currentColumnCount;
        gridLayout->addWidget(labels[i], row, column);
    }
}
