#include "download_action.h"

namespace NDaemonController {

    NJson::TJsonValue TDownloadAction::DoSerializeToJson() const {
        NJson::TJsonValue result(NJson::JSON_MAP);
        if (!WaitActionName)
            result.InsertValue("id_res", IdRes);
        return result;
    }

    void TDownloadAction::DoDeserializeFromJson(const NJson::TJsonValue& json) {
        NJson::TJsonValue::TMapType map;
        CHECK_WITH_LOG(json.GetMap(&map));
        if (!WaitActionName) {
            IdRes = map["id_res"].GetStringRobust();
        }
    }

    void TDownloadAction::InterpretTaskReply(TAsyncTaskExecutor::TTask::TStatus taskStatus, const NJson::TJsonValue& result) {
        if (result.Has("sky_progress")) {
            const NJson::TJsonValue& skyProgress = result["sky_progress"];
            TString hrInfo;
            for (ui32 i = 0; i < skyProgress.GetArray().size(); ++i) {
                const NJson::TJsonValue& skyProgressItem = skyProgress.GetArray()[i];
                if (hrInfo.size() > 0) {
                    hrInfo += '\n';
                }
                if (skyProgressItem.Has("error")) {
                    hrInfo += "#" + ToString(i) + " Failed: " + skyProgressItem["error"].GetStringRobust();
                } else {
                    if (taskStatus == TAsyncTaskExecutor::TTask::stsStarted) {
                        hrInfo += "#" + ToString(i) + ": Running";
                    } else if (taskStatus == TAsyncTaskExecutor::TTask::stsFailed) {
                        hrInfo += "#" + ToString(i) + ": Failed";
                    } else if (taskStatus == TAsyncTaskExecutor::TTask::stsFinished) {
                        hrInfo += "#" + ToString(i) + ": Completed";
                    }
                }
            }
            SetHRInfo(hrInfo);
        }
        TControllerAsyncAction::InterpretTaskReply(taskStatus, result);
    }

    TDownloadAction::TFactory::TRegistrator<TDownloadAction> TDownloadAction::Registrator(SYNC_DOWNLOAD_ACTION_NAME);
}
