#include "config_tab_worker.h"
#include <library/cpp/logger/global/global.h>
#include <util/string/vector.h>

namespace NRTYDeploy {
    using namespace NDMInterface;

    void TConfigTabWorker::FillTab(TConfigTab::TType tabType, TConfigTab& tab, IVersionedStorage& storage, const TProjectConfig::TComponent* component, const TProjectConfig& projectConfig) {
        THolder<TConfigTabWorker> worker(TFactory::Construct(tabType));
        if (worker)
            worker->FillTabImpl(tab, storage, component, projectConfig);
    }

    void TConfigTabWorker::SetChangedConfig(const TConfigTab& tab, IVersionedStorage& storage) {
        THolder<TConfigTabWorker> worker(TFactory::Construct(tab.GetType()));
        if(!worker)
            ythrow yexception() << "Don't know how to set config for " << tab.GetType();
        if (!tab.GetFilePath())
            ythrow yexception() << "file_path not set";
        if (tab.GetEnabled())
            worker->SetChangedConfigImpl(tab, storage);
        else
            storage.RemoveNode(tab.GetFilePath());
    }

    static const size_t MAX_DISPLAY_NAME_LENGTH = 25;

    void TConfigTabWorker::SetFieldName(TConfigField& field, const TString& name) {
        field.SetName(name);
        field.SetShowInSimpleForm(true);
        if (name.size() <= MAX_DISPLAY_NAME_LENGTH)
            field.SetDisplayName(name);
        else {
            TString dname;
            TVector<TString> nameSplit = SplitString(name, ".");
            dname = nameSplit.back();
            for (TVector<TString>::reverse_iterator i = nameSplit.rbegin() + 1; i != nameSplit.rend() && i->length() + dname.length() < MAX_DISPLAY_NAME_LENGTH; ++i)
                dname = *i + "." + dname;
            field.SetDisplayName("..." + dname);
        }
    }

    void TConfigTabWorker::SetFieldValue(TConfigField& field, const TString& value) {
        if (field.GetType() == TConfigField::BOOLEAN)
            field.SetValue(FromString<bool>(value) ? "true" : "false");
        else
            field.SetValue(value);
    }
}

template <>
void Out<NDMInterface::TConfigTab::TType>(IOutputStream& out, NDMInterface::TConfigTab::TType type) {
    out << NDMInterface::TConfigTab::descriptor()->enum_type(NDMInterface::TConfigTab::kTypeFieldNumber)->value(type)->name();
}
