#include "srcedit_defaulttext.h"
#include "keywordshighlighter.h"
#include <QComboBox>
#include <QFont>
#include <QGridLayout>
#include <QMenu>
#include <QSpinBox>
#include <QTextStream>

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



DefaultTextEdit:: DefaultTextEdit()
    :edit_square(new QTextEdit){}


void  DefaultTextEdit::modeReset(const QString &) const
{

}

QList<QString>  DefaultTextEdit::modes() const
{
    return QList<QString>() << "文本";
}

QString  DefaultTextEdit::currentMode() const
{
    return modes()[0];
}

void  DefaultTextEdit::jumpTo(const QList<QString> &path)
{

}

MakeTools::FilePresent::Features DefaultTextEdit::features()
{
    return Features();
}

std::tuple<bool, QString>  DefaultTextEdit::create(const QDir &target, const QString &name, const QString &suffix)
{
    auto x = target.filePath(QString("%1.%2").arg(name, suffix));
    if(QFileInfo::exists(x))
        return std::make_tuple(false, x);

    QFile xf(x);
    if(!xf.open(QIODevice::WriteOnly|QIODevice::Text))
        throw new std::exception(QString("指定文件无法建立：" + x).toLocal8Bit());

    return std::make_tuple(true, target.relativeFilePath(x));
}

MakeTools::FilePresent * DefaultTextEdit::newInst() const
{
    return new  DefaultTextEdit();
}

void  DefaultTextEdit::applySetting(const QString &name, Core::AppCore *core)
{
    name_store = name;
}

QString  DefaultTextEdit::name() const
{
    return name_store;
}

void  DefaultTextEdit::load(const QFileInfo &target_file)
{
    if(!target_file.exists())
        throw new std::exception(QString("指定文件未找到：%1").arg(target_file.absoluteFilePath()).toLocal8Bit());

    target_file_path = target_file.canonicalFilePath();
    QFile bin(target_file_path);
    if(!bin.open(QIODevice::ReadOnly | QIODevice::Text))
        throw new std::exception(QString("指定文件无法打开：%1").arg(target_file.absoluteFilePath()).toLocal8Bit());

    QTextStream tin(&bin);
    tin.setCodec("UTF-8");
    auto content = tin.readAll();
    this->edit_square->setText(content);
}

void  DefaultTextEdit::saveAs(const QString &path)
{
    if(!path.isEmpty())
        target_file_path = path;

    QFile bout(target_file_path);
    if(!bout.open(QIODevice::WriteOnly|QIODevice::Text))
        throw new std::exception(QString("指定文件无法打开：%1").arg(target_file_path).toLocal8Bit());

    QTextStream tout(&bout);
    tout.setCodec("UTF-8");
    tout << this->edit_square->toPlainText();
    tout.flush();
}

QString  DefaultTextEdit::relativeTargetPath(const QDir &base) const
{
    if(target_file_path == "")
        return "";

    return base.relativeFilePath(target_file_path);
}

bool  DefaultTextEdit::isModified() const
{
    return true;
}

QList<QString>  DefaultTextEdit::suffixes() const
{
    return QStringList() << "txt" << "*";
}

QString  DefaultTextEdit::absoluteTargetPath() const
{
    return target_file_path;
}


QWidget * DefaultTextEdit::widget() const
{
    return edit_square;
}
