#include "appcore.h"
#include "DocsManager.h"
#include "mainwindow.h"
#include "manager_docs.h"
#include "srcedit_storyboard.h"
#include "srcedit_storychain.h"
#include "srcedit_storyconcept.h"
#include "srcedit_storyunit.h"
#include "srcedit_storyvolume.h"
#include "xapp.h"
#include "xmlconfig.h"

#include <QMessageBox>
#include <QTextStream>
#include <StoryTool.h>

using namespace Core;
using namespace Components;
using namespace Parse::Result;
using namespace MakeTools;

AppCore::AppCore(QObject *parent) : QObject(parent), global_config(new Config::XMLConfig(this)), makes_core(new StoryTool()) {
    global_config->loadFile(QDir(QApplication::applicationDirPath()).filePath(".software.xml"));

    auto ins0 = new StorychainSourceEdit();
    auto ins1 = new StoryunitSourceEdit();
    auto ins2 = new StoryboardSourceEdit();
    auto ins3 = new StoryvolumeSourceEdit();
    auto ins4 = new StoryconceptSourceEdit();
    registerHighlightType(ins0);
    registerHighlightType(ins1);
    registerHighlightType(ins2);
    registerHighlightType(ins3);
    registerHighlightType(ins4);


    present_types << ins0 << ins1 << ins2 << ins3 << ins4
                    << new  DefaultTextEdit();
}

void AppCore::registerHighlightType(Enhancement::HighlightFeature *base_type)
{
    render_types << base_type;
}

bool AppCore::isHighlightDemand(void *ins) const
{
    return render_types.contains((Enhancement::HighlightFeature*)ins);
}

QList<FilePresent *> AppCore::allViews() const
{
    return present_types;
}

void AppCore::save()
{
    global_config->save();
}

Config::Configration *AppCore::globalConfig() const
{
    return global_config;
}

void AppCore::setCurrentProject(Project::ProjectManager *project)
{
    this->current_project = project;
}

Project::ProjectManager *AppCore::currentProject() const
{
    return this->current_project;
}

QList<Config::Configration *> AppCore::getConfigs(QList<Scale> types) const
{
    QList<Config::Configration*> rets;

    for(auto &x : types){
        if(x == Scale::Global)
            rets << global_config;
        if(x == Scale::Project && current_project->isOpen())
            rets << current_project->configraions();
    }

    return rets;
}

Parse::Result::ParseCore *AppCore::parseCore() const
{
    return makes_core->getCore();
}

QList<FilePresent *> AppCore::extensions(const QString &suffix) const
{
    if(suffix.isEmpty())
        return this->present_types;

    QList<FilePresent*> rets;
    for(auto &ext : present_types)
        if(ext->suffixes().contains(suffix))
            rets << ext;

    for(auto &ext : present_types)
        if(ext->suffixes().contains("*"))
            rets << ext;

    return rets;
}

MakeTools::StoryTool *AppCore::getMakeCore() const
{
    return makes_core;
}

QString AppCore::name() const
{
    return NAME(AppCore);
}




SimpleException::SimpleException(const QString &msg)
    : msg_store(msg) {}

const char *SimpleException::what() const{
    return msg_store.toLocal8Bit();
}
