/* -*- Mode: C++; indent-tabs-mode: nil; tab-width: 4 -*-
 * -*- coding: utf-8 -*-
 *
 * Copyright (C) 2025 KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published
 * the Free Software Foundation, either version 3 of the License, or
 * 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, see <http://www.gnu.org/licenses/>.
 */

#ifndef IJSON_H
#define IJSON_H

#include <nlohmann/json.hpp>
#include <iostream>
#include <fstream>
#include <filesystem>
#include <iomanip>

namespace UkuiAudioFramwork
{
template <typename T>
class IJson
{
public:
    IJson() = default;

    virtual ~IJson() = default;

public:
    virtual bool isContain(const T&) const = 0;

    virtual void insert(const T&) = 0;

protected:
    void loadJson()
    {
        std::ifstream file(m_fileName);
        if (file.is_open()) {
            /** Initializing nlohmann json without throwing exceptions */
            m_json = nlohmann::json::parse(file, nullptr, false);

            /** Check again whether json is a valid json file to prevent abnormal
             * situations caused by the user's file status */
            if (!m_json.is_object()) {
                m_json = nlohmann::json::object();
            }
        } else {
            m_json = nlohmann::json::object();
        }
    }

    void writeToJson()
    {
        std::filesystem::create_directories(std::filesystem::path(m_fileName).parent_path());
        std::ofstream outFile(m_fileName);
        if (!outFile) {
            std::cerr << "Unable to open " << m_fileName << " for writing." << std::endl;
            return;
        }
        outFile << std::setw(4) << m_json << std::endl;
    }

protected:
    mutable std::string m_fileName;
    mutable nlohmann::json m_json;
};
}
#endif // IJSON_H
