/*
 * Copyright 2020 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.
 */

#ifndef INCLUDED_BUILDBOXCASD_FSLOCALASSETSTORAGE_H
#define INCLUDED_BUILDBOXCASD_FSLOCALASSETSTORAGE_H

#include <string>

#include <buildboxcommon_protos.h>

namespace buildboxcasd {

using namespace build::bazel::remote::asset::v1;
using namespace build::bazel::remote::execution::v2;

class FsLocalAssetStorage final {
    /* Implements a local asset storage providing a mapping from asset
     * identifiers to CAS digests.
     */
  public:
    explicit FsLocalAssetStorage(const std::string &root_path);

    bool lookup(const FetchBlobRequest &request, FetchBlobResponse *response);
    bool lookup(const FetchDirectoryRequest &request,
                FetchDirectoryResponse *response);

    void insert(const PushBlobRequest &request);
    void insert(const PushDirectoryRequest &request);

    // default destructor
    ~FsLocalAssetStorage() = default;

    // delete copy and move constructors and assignment operators
    FsLocalAssetStorage(const FsLocalAssetStorage &) = delete;
    FsLocalAssetStorage &operator=(const FsLocalAssetStorage &) = delete;
    FsLocalAssetStorage(FsLocalAssetStorage &&) = delete;
    FsLocalAssetStorage &operator=(FsLocalAssetStorage &&) = delete;

  private:
    const std::string d_storage_root;
    const std::string d_objects_directory;
    const std::string d_temp_directory;

    std::string filePath(const google::protobuf::Message &key,
                         bool create_parent_directory = false);

    bool readMessage(const google::protobuf::Message &key,
                     google::protobuf::Message *value);
    void writeMessage(const google::protobuf::Message &key,
                      const google::protobuf::Message &value);
    void deleteMessage(const google::protobuf::Message &key);

    // Number of most significant hash characters to take for top-level
    // directory names:
    static const int s_HASH_PREFIX_LENGTH;
};

} // namespace buildboxcasd

#endif // INCLUDED_BUILDBOXCASD_FSLOCALASSETSTORAGE_H
