#include "normalizer.h"

namespace NRTYServer {

    TNormalizersCollection::TNormalizersCollection(const TRTYServerConfig& config)
            : INormalizer(config)
        {}

        void TNormalizersCollection::Register(const TAtomicSharedPtr<INormalizer>& normalizer) {
            Normalizers.push_back(normalizer);
        }

        void TNormalizersCollection::Clear() {
            Normalizers.clear();
        }

        const char* TNormalizersCollection::Name() const {
            return "Normalizers collection";
        }

        void TNormalizersCollection::CheckAndFix(const NRTYServer::TNormalizerContext& context, const THolder<TFileMap>& indexFrq) const {
            const TString indexDir = context.Dir.PathName();
            for (TNormalizers::const_iterator i = Normalizers.begin(); i != Normalizers.end(); ++i) {
                INFO_LOG << (*i)->Name() << " checking (" << indexDir << ") ... " << Endl;
                if (!(*i)->AllRight(context, indexFrq)) {
                    INFO_LOG << (*i)->Name() << " checking (" << indexDir << ") ... FAILED" << Endl;
                    INFO_LOG << (*i)->Name() << " repairing (" << indexDir << ") ..." << Endl;
                    (*i)->Fix(context, indexFrq);
                    INFO_LOG << (*i)->Name() << " repairing (" << indexDir << ") ... OK" << Endl;
                } else
                    INFO_LOG << (*i)->Name() << " checking (" << indexDir << ") ... OK" << Endl;
            }
        }

        void TNormalizersCollection::Fix(const NRTYServer::TNormalizerContext& context, const THolder<TFileMap>& indexFrq) const {
            CheckAndFix(context, indexFrq);
        }

        bool TNormalizersCollection::AllRight(const NRTYServer::TNormalizerContext& context, const THolder<TFileMap>& indexFrq) const {
            const TString indexDir = context.Dir.PathName();
            for (TNormalizers::const_iterator i = Normalizers.begin(); i != Normalizers.end(); ++i) {
                INFO_LOG << (*i)->Name() << " checking (" << indexDir << ") ... " << Endl;
                if (!(*i)->AllRight(context, indexFrq)) {
                    INFO_LOG << (*i)->Name() << " checking (" << indexDir << ") ... FAILED" << Endl;
                    return false;
                } else
                    INFO_LOG << (*i)->Name() << " checking (" << indexDir << ") ... OK" << Endl;
            }
            return true;
        }

        TString TNormalizersCollection::GetNormalizersNames() const {
            TString result;
            for (const auto& normalizer : Normalizers) {
                if (result)
                    result.append(";");
                result.append(normalizer->Name());
            }
            return result;
        }

}
