#include "{header}.h"

{{ if allow_instrumentation }}
{{ if readwrite- }}
#include <unistd.h>
#include "aconfig_storage/aconfig_storage_read_api.hpp"
#include <android/log.h>
#define LOG_TAG "aconfig_cpp_codegen"
#define ALOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
{{ -endif }}
{{ endif }}

{{ if readwrite- }}
#include <server_configurable_flags/get_flags.h>
{{ endif }}
{{ if is_test_mode }}
#include <unordered_map>
#include <string>
{{ -else- }}
{{ if readwrite- }}
#include <vector>
{{ -endif }}
{{ -endif }}

namespace {cpp_namespace} \{

{{ if is_test_mode }}
    class flag_provider : public flag_provider_interface \{
    private:
        std::unordered_map<std::string, bool> overrides_;

    public:
        flag_provider()
            : overrides_()
        \{}

{{ for item in class_elements }}
        virtual bool {item.flag_name}() override \{
            auto it = overrides_.find("{item.flag_name}");
              if (it != overrides_.end()) \{
                  return it->second;
            } else \{
              {{ if item.readwrite- }}
              return server_configurable_flags::GetServerConfigurableFlag(
                  "aconfig_flags.{item.device_config_namespace}",
                  "{item.device_config_flag}",
                  "{item.default_value}") == "true";
              {{ -else }}
                  return {item.default_value};
              {{ -endif }}
            }
        }

        virtual void {item.flag_name}(bool val) override \{
            overrides_["{item.flag_name}"] = val;
        }
{{ endfor }}

        virtual void reset_flags() override \{
            overrides_.clear();
        }
    };

{{ -else- }}

    class flag_provider : public flag_provider_interface \{
    public:

        {{ if allow_instrumentation- }}
        {{ if readwrite- }}
        flag_provider()
            {{ if readwrite- }}
            : cache_({readwrite_count}, -1)
            , boolean_start_index_()
            {{ -else- }}
            : boolean_start_index_()
            {{ -endif }}
            , flag_value_file_(nullptr)
            , read_from_new_storage_(false) \{

            if (access("/metadata/aconfig/boot/enable_only_new_storage", F_OK) == 0) \{
               read_from_new_storage_ = true;
            }

            if (!read_from_new_storage_) \{
               return;
            }

            auto package_map_file = aconfig_storage::get_mapped_file(
                 "{container}",
                 aconfig_storage::StorageFileType::package_map);
            if (!package_map_file.ok()) \{
                ALOGE("error: failed to get package map file: %s", package_map_file.error().c_str());
            }

            auto context = aconfig_storage::get_package_read_context(
                **package_map_file, "{package}");
            if (!context.ok()) \{
                ALOGE("error: failed to get package read context: %s", context.error().c_str());
            }

            // cache package boolean flag start index
            boolean_start_index_ = context->boolean_start_index;

            // unmap package map file and free memory
            delete *package_map_file;

            auto flag_value_file = aconfig_storage::get_mapped_file(
                "{container}",
                aconfig_storage::StorageFileType::flag_val);
            if (!flag_value_file.ok()) \{
                ALOGE("error: failed to get flag value file: %s", flag_value_file.error().c_str());
            }

            // cache flag value file
            flag_value_file_ = std::unique_ptr<aconfig_storage::MappedStorageFile>(
                *flag_value_file);

        }
        {{ -endif }}
        {{ -endif }}

        {{ -for item in class_elements }}
        virtual bool {item.flag_name}() override \{
            {{ -if item.readwrite }}
            if (cache_[{item.readwrite_idx}] == -1) \{
            {{ if allow_instrumentation- }}
                if (read_from_new_storage_) \{
                    auto value = aconfig_storage::get_boolean_flag_value(
                        *flag_value_file_,
                        boolean_start_index_ + {item.flag_offset});

                    if (!value.ok()) \{
                        ALOGE("error: failed to read flag value: %s", value.error().c_str());
                    }

                    cache_[{item.readwrite_idx}] = *value;
                } else \{
                    cache_[{item.readwrite_idx}] = server_configurable_flags::GetServerConfigurableFlag(
                        "aconfig_flags.{item.device_config_namespace}",
                        "{item.device_config_flag}",
                        "{item.default_value}") == "true";
                }
            {{ -else- }}
                cache_[{item.readwrite_idx}] = server_configurable_flags::GetServerConfigurableFlag(
                    "aconfig_flags.{item.device_config_namespace}",
                    "{item.device_config_flag}",
                    "{item.default_value}") == "true";
            {{ -endif }}
            }
            return cache_[{item.readwrite_idx}];
            {{ -else }}
            {{ -if item.is_fixed_read_only }}
            return {package_macro}_{item.flag_macro};
            {{ -else }}
            return {item.default_value};
            {{ -endif }}
            {{ -endif }}
        }
        {{ -endfor }}

    {{ if readwrite- }}
    private:
        std::vector<int8_t> cache_ = std::vector<int8_t>({readwrite_count}, -1);
    {{ if allow_instrumentation- }}
        uint32_t boolean_start_index_;

        std::unique_ptr<aconfig_storage::MappedStorageFile> flag_value_file_;

        bool read_from_new_storage_;
    {{ -endif }}
    {{ -endif }}

    };

{{ -endif }}

std::unique_ptr<flag_provider_interface> provider_ =
    std::make_unique<flag_provider>();
}

{{ for item in class_elements }}
bool {header}_{item.flag_name}() \{
    {{ -if is_test_mode }}
    return {cpp_namespace}::{item.flag_name}();
    {{ -else }}
    {{ -if item.readwrite }}
    return {cpp_namespace}::{item.flag_name}();
    {{ -else }}
    {{ -if item.is_fixed_read_only }}
    return {package_macro}_{item.flag_macro};
    {{ -else }}
    return {item.default_value};
    {{ -endif }}
    {{ -endif }}
    {{ -endif }}
}

{{ -if is_test_mode }}
void set_{header}_{item.flag_name}(bool val) \{
    {cpp_namespace}::{item.flag_name}(val);
}
{{ -endif }}
{{ endfor }}

{{ -if is_test_mode }}
void {header}_reset_flags() \{
     {cpp_namespace}::reset_flags();
}
{{ -endif }}
