/*
 * BSD 2-Clause License
 *
 * Copyright (c) 2020, Agnieszka Cicha-Cisek
 * Copyright (c) 2020, Patryk Cisek
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <boost/log/trivial.hpp>

#include <QGuiApplication>
#include <QImage>
#include <QSize>
#include <QToolButton>
#include <QScreen>

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include "authenticatedialog.h"
#include "authentication.h"
#include "totpconverter.h"
#include "totpuriparser.h"

#include "nitrokeybase.h"

MainWindow::MainWindow(std::shared_ptr<KeyTOTPModel> model,
                       QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    model(model),
    errorMessage(),
    aboutNitrokeyDialog(this),
    screenshotter(windowHandle())
{
    ui->setupUi(this);
    connect(ui->addSecret, &QToolButton::clicked, this, &MainWindow::onAddSecretClicked, Qt::QueuedConnection);
    connect(ui->eraseSecret, &QToolButton::clicked, model.get(), &KeyTOTPModel::onEraseSelectedSlot);
    connect(ui->copy, &QToolButton::clicked, this, &MainWindow::onCopyClicked, Qt::QueuedConnection);
    constexpr int ITEM_WITH = 285;
    constexpr int ITEM_HEIGHT = 90;
    ui->listView->setViewMode(QListView::IconMode);
    ui->listView->setIconSize(QSize(ITEM_WITH, ITEM_HEIGHT));
    ui->listView->setGridSize(QSize(ITEM_WITH, ITEM_HEIGHT));
    ui->listView->setSpacing(0);

    ui->listView->setModel(model.get());
    connect(model.get(), &KeyTOTPModel::userAuthenticationFailed,
            this, &MainWindow::onUserAuthenticationFailed, Qt::QueuedConnection);
    connect(model.get(), &KeyTOTPModel::userAuthenticationCanceled,
            this, &MainWindow::onUserAuthenticationCanceled, Qt::QueuedConnection);

    connect(model.get(), &KeyTOTPModel::totpCodePresent,
            ui->copy, &QToolButton::setEnabled);

    connect(model.get(), &KeyTOTPModel::connectionStateChanged,
            ui->addSecret, &QToolButton::setEnabled);

    model->setItemSize(QSize(ITEM_WITH, ITEM_HEIGHT));

    connect(ui->listView->selectionModel(), &QItemSelectionModel::currentChanged,
            model.get(), &KeyTOTPModel::onSlotSelected);
    connect(ui->listView->selectionModel(), &QItemSelectionModel::currentChanged,
            this, &MainWindow::onSlotSelected);

    connect(ui->action_About_Nitrokey_Authenticator, &QAction::triggered,
                  this, &MainWindow::onAboutNitrokeyAuthenticator);

    connect(&screenshotter, &Screenshotter::qrCodeDecoded,
            this, &MainWindow::onQRCodeDecoded);
    connect(&screenshotter, &Screenshotter::qrCodeDetectionError,
            this, &MainWindow::onQrCodeDetectionError);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::onAddSecretClicked()
{
    BOOST_LOG_TRIVIAL(debug) << "Adding secret...";

    screenshotter.takeScreenshot();

    ui->addSecret->setDisabled(true);
}

void MainWindow::onQRCodeDecoded(const QString &text)
{
    BOOST_LOG_TRIVIAL(trace) << "Decoded text: " << text.toStdString();
    ui->addSecret->setEnabled(true);
    const QString ZBAR_DECODED_PREFIX("QR-Code:");
    if (!text.startsWith(ZBAR_DECODED_PREFIX)) {
        // error
        errorMessage.showMessage("The QR-Code detected, but format unrecognized!");
    } else {
        const QString QR_CODE_DECODED = text.right(text.length() - ZBAR_DECODED_PREFIX.length());
        BOOST_LOG_TRIVIAL(trace) << "QR_CODE_DECODED:" << QR_CODE_DECODED.toStdString();
        TotpUriParser parser(QR_CODE_DECODED);
        TotpConverter secretConverter;
        BOOST_LOG_TRIVIAL(trace) << "parsed account name: " << parser.getAccountName().toStdString()
                                 << " parsed issuer: " << parser.getIssuer().toStdString()
                                 << " parsed secret: " << parser.getSecret().toStdString()
                                 << " parsed and converted secret: "
                                 << secretConverter.convertBase32ToHex(parser.getSecret()).toStdString();
        model->addNewSlot(std::unique_ptr<TotpUriParser>(new TotpUriParser(QR_CODE_DECODED)));
    }
}

void MainWindow::onSlotSelected()
{
    ui->eraseSecret->setEnabled(true);
}

void MainWindow::onUserAuthenticationCanceled()
{
    BOOST_LOG_TRIVIAL(info) << "onUserAuthenticationCanceled(). Clearing model selection.";
    ui->listView->clearSelection();
    ui->listView->setCurrentIndex(QModelIndex());
}

void MainWindow::onUserAuthenticationFailed()
{
    BOOST_LOG_TRIVIAL(warning) << "onUserAuthenticationFailed(). Clearing model selection.";
    ui->listView->clearSelection();
    ui->listView->setCurrentIndex(QModelIndex());
}

void MainWindow::onQrCodeDetectionError()
{
    BOOST_LOG_TRIVIAL(warning) << "onQrCodeTimerTimeout(). Could not detect QR-Code";
    QMessageBox::warning(nullptr, tr("QR-Code detection failed"),
                         tr("Wasn't able to detect the QR-Code on the screen. Please make\n"
                            "sure, the QR-Code is visible on your screen and try again."));
    ui->addSecret->setEnabled(true);
}

void MainWindow::onAboutNitrokeyAuthenticator()
{
    BOOST_LOG_TRIVIAL(debug) << "About NitrokeyAuthenticator.";
    aboutNitrokeyDialog.exec();
}

void MainWindow::onCopyClicked() const
{
    BOOST_LOG_TRIVIAL(debug) << "Copying TOTP code: "
                             << model->currentlySelectedTOTPCode().toStdString()
                             << " to clipboard.";
    QGuiApplication::clipboard()->setText(model->currentlySelectedTOTPCode());
}

void MainWindow::onNewScreenshot()
{
    BOOST_LOG_TRIVIAL(debug) << "Received new screenshot.";
}
