/***
   This file is part of fly-ocr.

   Copyright (C) 2021 LLC "RusBITech-Astra" (https://astralinux.ru)

   Foobar is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   Foobar is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with fly-ocr. If not, see <https://www.gnu.org/licenses/>.
***/

#include <QSet>
#include "languageselectiondialog.h"
#include "ui_languageselectiondialog.h"

LanguageSelectionDialog::LanguageSelectionDialog(const QList<FlyOcr::Lang>& langs, const QList<FlyOcr::Lang>& selectedLangs, QWidget* parent) :
    QDialog(parent),
    m_ui(new Ui::LanguageSelectionDialog)
{
    m_ui->setupUi(this);

    QSet<QString> selectedLangNames;
    for (const FlyOcr::Lang& l : qAsConst(selectedLangs)) {
        QListWidgetItem* item = new QListWidgetItem(m_ui->selectedLangListWidget);
        item->setText(l.name);
        item->setData(LangCodeRole, l.code);
        item->setData(ShortNameRole, l.shortName);
        selectedLangNames.insert(l.shortName);
    }

    for (const FlyOcr::Lang& l : qAsConst(langs)) {
        if (!selectedLangNames.contains(l.shortName)) {
            QListWidgetItem* item = new QListWidgetItem(m_ui->langListWidget);
            item->setText(l.name);
            item->setData(LangCodeRole, l.code);
            item->setData(ShortNameRole, l.shortName);
            m_ui->langListWidget->addItem(item);
        }
    }

    m_ui->langSearchLine->setListWidget(m_ui->langListWidget);
}

LanguageSelectionDialog::~LanguageSelectionDialog()
{
    delete m_ui;
}

QList<FlyOcr::Lang> LanguageSelectionDialog::selectedLaguages() const
{
    QList<FlyOcr::Lang> out;
    for (int row = 0; row < m_ui->selectedLangListWidget->count(); ++row) {
        QListWidgetItem* item = m_ui->selectedLangListWidget->item(row);
        FlyOcr::Lang l = {
            .shortName = item->data(ShortNameRole).toString(),
            .code = item->data(LangCodeRole).toString(),
            .name = item->text()
        };

        out << l;
    }

    return out;
}

void LanguageSelectionDialog::on_addButton_clicked()
{
    if (m_ui->langListWidget->currentRow() >= 0) {
        m_ui->selectedLangListWidget->addItem(m_ui->langListWidget->takeItem(m_ui->langListWidget->currentRow()));
    }
}

void LanguageSelectionDialog::on_removeButton_clicked()
{
    if (m_ui->selectedLangListWidget->currentRow() >= 0) {
        m_ui->langListWidget->addItem(m_ui->selectedLangListWidget->takeItem(m_ui->selectedLangListWidget->currentRow()));
    }
}
