#include "qmoviedb.h"
#include "QNetworkReply"
#include "QDebug"
#include "QJsonDocument"
#include "QJsonObject"
#include "QJsonArray"

QMovieDB::QMovieDB(QString apiKey, QObject *parent)
    : QObject{parent}, netMan(new QNetworkAccessManager(this)) {
    movieDbApiKey = apiKey;
    QObject::connect(netMan, &QNetworkAccessManager::finished, this, &QMovieDB::receiveReply);
}

void QMovieDB::searchMovieTitle(const QString title)
{
    QNetworkRequest req;
    req.setRawHeader("Accept", "application/json");

    QString bearer = "Bearer " + movieDbApiKey;
    req.setRawHeader("Authorization", bearer.toUtf8());

    QByteArray URL = QUrl::toPercentEncoding(title);
    URL = "https://api.themoviedb.org/3/search/movie?query=" + URL + "&include_adult=false&language=en-US&page=1";

    req.setUrl(QUrl(URL));
    netMan->get(req);
}

void QMovieDB::receiveReply(QNetworkReply *reply) {
    int responseStatus = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

    if (responseStatus == 200) {
        parseResults(QJsonDocument::fromJson(reply->readAll()).object());
    } else {
        qWarning() << "Invalid Response. Status: " << responseStatus;
    }
}

void QMovieDB::parseResults(QJsonObject json) {
    qInfo() << "Total Results: " << json.value("total_results").toInt();

    QJsonArray results = json.value("results").toArray(); //Even if single result, always returns array of result(s).

    for (int i = 0; i < results.size(); i++) {
        QString releaseYear = results.at(i).toObject().value("release_date").toString();
        releaseYear = "(" + releaseYear.left(releaseYear.indexOf("-")) + ")";
        QString titleYear = results.at(i).toObject().value("title").toString() + " " + releaseYear;

        qInfo() << "Result " << (i + 1) << ": " << titleYear;
    }


}
