/******************************************************************************
*	File		-	project.cpp
*	Author		-	Joey Pollack
*	Date		-	2021/11/09 (y/m/d)
*	Mod Date	-	2021/11/09 (y/m/d)
*	Description	-	Manage data for a game project
******************************************************************************/

#include "project.h"

#include <pugixml.hpp>

namespace lunarium
{
    Project::Project()
        : mIsLoaded(false)
    {

    }

    OpRes Project::GenerateProject(std::string name, std::filesystem::path location)
    {
        if (mIsLoaded)
        {
            return OpRes::Fail("A project is already loaded. Unload the current project to generate a new one.");
        }

        mName = name;
        mLocation = location;
        mLocation /= mName;

        if (std::filesystem::exists(mLocation))
        {
            return OpRes::Fail("A project with that name (%s) already exists in this location: %s", mName.c_str(), mLocation.string().c_str());
        }

        std::filesystem::create_directory(mLocation);

        std::filesystem::path proj_doc = mLocation;
        proj_doc /= std::filesystem::path(mName + ".lproj");
        
        pugi::xml_document doc;
        pugi::xml_node proj_node = doc.append_child("Lunarium_Project");
        proj_node.append_attribute("name").set_value(mName.c_str());
        //pugi::xml_node name_node = proj_node.append_child("Name");
        doc.save_file(proj_doc.string().c_str());

        std::filesystem::create_directory(mLocation / std::filesystem::path("engine"));
        std::filesystem::create_directory(mLocation / std::filesystem::path("contents"));
        std::filesystem::create_directory(mLocation / std::filesystem::path("contents/assets"));

        mIsLoaded = true;
        return OpRes::OK();
    }

    bool Project::IsLoaded() const
    {
        return mIsLoaded;
    }

    OpRes Project::LoadProject(std::filesystem::path location)
    {
        if (!std::filesystem::exists(location))
        {
            return OpRes::Fail("Project file does not exist");
        }

        mLocation = location;
        mName = location.filename().string();

        mIsLoaded = true;
        return OpRes::OK();
    }

    void Project::UnloadCurrentProject()
    {
        mName = "";
        mLocation = "";
        mIsLoaded = false;
    }

    
    const std::string& Project::GetName() const
    {
        return mName;
    }

    std::filesystem::path Project::GetRootDirectory() const
    {
        return mLocation;
    }
}