/*
 *   This file is part of Dianara
 *   Copyright 2012-2019  JanKusanagi JRR <jancoding@gmx.com>
 *
 *   This program 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 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program 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 this program; if not, write to the
 *   Free Software Foundation, Inc.,
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA .
 */

#include "datafile.h"


DataFile::DataFile(QString filename, QObject *parent) : QObject(parent)
{
    m_dataFile = new QFile(filename);
    if (!m_dataFile->exists())
    {
        // Initialize empty file
        if (!m_dataFile->open(QIODevice::WriteOnly))
        {
            qDebug() << "** Error initializing data file: " << filename;
        }

        m_dataFile->write(QByteArray());
        m_dataFile->close();
    }


    qDebug() << "DataFile created for " << filename;
}


DataFile::~DataFile()
{
    qDebug() << "DataFile destroyed for " << m_dataFile->fileName();
}


/*
 * Read map list data from disk in JSON format.
 *
 */
QVariantList DataFile::loadData()
{
    QVariantList loadedList;
    bool parsedOk = false;

    m_dataFile->open(QIODevice::ReadOnly);

    const QByteArray rawData = m_dataFile->readAll();
    m_dataFile->close();

    QJsonDocument jsonDocument;
    jsonDocument = QJsonDocument::fromJson(rawData);
    loadedList = jsonDocument.toVariant().toList();
    parsedOk = !jsonDocument.isNull();

    if (!parsedOk)
    {
        // TMP FIXME
        loadedList.clear();
        qDebug() << "** Error parsing JSON file";
    }

    return loadedList;
}


/*
 * Save VariantList data to disk in JSON format.
 *
 */
bool DataFile::saveData(QVariantList list)
{
    QByteArray byteData;

    QJsonDocument jsonDocument;
    jsonDocument = QJsonDocument::fromVariant(list);
    byteData = jsonDocument.toJson(QJsonDocument::Indented);


    m_dataFile->open(QIODevice::WriteOnly);
    int written = m_dataFile->write(byteData);
    m_dataFile->close();

    if (written < 1) // 0 bytes, or -1 for Error
    {
        return false;
    }

    return true;
}

