/*
 * Copyright 2018 Bloomberg Finance LP
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <buildboxworker_config.h>
#include <worker_config.grpc.pb.h>

#include <buildboxcommon_logging.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/text_format.h>

#include <fstream>

#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

namespace buildboxworker {

proto::BotStatus Config::getStatusFromConfigStream(std::istream *stream)
{
    WorkerConfig workerConfig;
    google::protobuf::io::IstreamInputStream streamInput(stream);
    if (!google::protobuf::TextFormat::Parse(&streamInput, &workerConfig) ||
        !proto::BotStatus_IsValid(workerConfig.botstatus())) {
        BUILDBOX_LOG_ERROR("Failed parsing config, defaulting to status="
                           << proto::BotStatus::OK);
        return proto::BotStatus::OK;
    }

    return workerConfig.botstatus();
}

proto::BotStatus
Config::getStatusFromConfigFile(const std::string &configFileName)
{
    if (configFileName.empty()) {
        BUILDBOX_LOG_INFO("Path to config file is empty, defaulting to status "
                          << proto::BotStatus::OK);
        return proto::BotStatus::OK;
    }

    std::ifstream ifstream(configFileName, std::ios::in);
    if (!ifstream) {
        BUILDBOX_LOG_ERROR(
            "Error opening config file in \""
            << configFileName << "\" failbit=" << ifstream.fail()
            << ", badbit=" << ifstream.bad()
            << ", defaulting to status=" << proto::BotStatus::OK);
        return proto::BotStatus::OK;
    }

    const proto::BotStatus botStatus = getStatusFromConfigStream(&ifstream);
    BUILDBOX_LOG_INFO("Bot status read from \"" << configFileName << "\" is "
                                                << botStatus);

    return botStatus;
}

} // namespace buildboxworker
