/*
 * 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_BUILDBOXCOMMON_OBJECTSUBDIRSFDSTORE_H
#define INCLUDED_BUILDBOXCOMMON_OBJECTSUBDIRSFDSTORE_H

#include <string>
#include <vector>

#include <buildboxcommon_fileutils.h>

namespace buildboxcommon {

class ObjectSubDirsFDStore {

  public:
    ObjectSubDirsFDStore(int hash_prefix_length,
                         const std::string &obj_dir_path);

    /*
     * Returns object subdirectory file descriptor associated with hash.
     * Do not close the file descriptor which is returned.
     */
    int getSubDirFDFromHash(const std::string &hash) const;
    // default destructor
    ~ObjectSubDirsFDStore() = default;
    // disallow copy and move semantics
    ObjectSubDirsFDStore(const ObjectSubDirsFDStore &) = delete;
    ObjectSubDirsFDStore &operator=(const ObjectSubDirsFDStore &) = delete;
    ObjectSubDirsFDStore(ObjectSubDirsFDStore &&) = delete;
    ObjectSubDirsFDStore &operator=(ObjectSubDirsFDStore &&) = delete;

  private:
    const int d_hash_prefix_length;
    const int d_num_sub_dirs;
    const std::string d_obj_dir_path;

    // A vector which should contain open directory file descriptors.
    // The vector will be the same size as the number of object subdirectories
    // in local cache. Where index i contains the
    // file descriptor corresponding to the object subdirectory
    // hex(i) (i.e index 0 -> 00, index 255 -> ff, etc.)
    std::vector<buildboxcommon::FileDescriptor> d_objects_dirfd;

    /*
     * Create object subdirectories. Then store the file
     * descriptors for each subdirectory in d_objects_dirfd
     */
    void createAndStoreObjectSubDirFDs(int objects_dirfd);
};

} // namespace buildboxcommon

#endif // INCLUDED_BUILDBOXCOMMON_OBJECTSUBDIRSFDSTORE_H
