/*
 * Copyright 2021 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_FSLOCALACSTORAGE_H
#define INCLUDED_BUILDBOXCASD_FSLOCALACSTORAGE_H

#include <buildboxcasd_actionstorage.h>
#include <buildboxcommon_protos.h>
#include <string>

namespace buildboxcasd {
using namespace build::bazel::remote::execution::v2;
using namespace google::protobuf;
using namespace build::buildgrid;

class FsLocalActionStorage final : public ActionStorage {
    /* Implements the reAPI ActionCache's local storage option
     */
  public:
    /* Creates the storage directory if not present and
     * initializes the object.
     */
    FsLocalActionStorage(const std::string &path);
    ~FsLocalActionStorage() override = default;

    /* Creates a file storing a serialized Action Digest and its
     * corresponding ActionResult. Replaces the old result
     * if action_digest is already stored.
     */
    void storeAction(const Digest &action_digest,
                     const ActionResult &result) override;

    /* Reads the file named action_digest and copies
     * its corresponding ActionResult into result.
     * Returns true if successful and false otherwise.
     */
    bool readAction(const Digest &action_digest,
                    ActionResult *result) override;

  private:
    std::string d_storageRoot;
    std::string d_objectsDirectory;
    std::string d_tempDirectory;

    std::string filePath(const Digest &actionDigest,
                         bool createParentDirectory = false);

    // 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_FSLOCALACSTORAGE_H
