# SPDX-FileCopyrightText: 2024 Google LLC
# SPDX-License-Identifier: Apache-2.0

from waflib import Task, TaskGen


class pfs_resources_table(Task.Task):
    def run(self):
        with open(self.outputs[0].abspath(), 'w') as f:
            f.write("""
//
// AUTOGENERATED
// DO NOT MODIFY
//

#include "resource/resource_storage_file.h"
""")

            fw_bld_node = self.generator.bld.bldnode.find_node('src/fw')
            f.write('#include "{}"\n'.format(self.resource_id_header.path_from(fw_bld_node)))
            f.write('\n')

            f.write('const uint32_t g_num_file_resource_stores = {};\n'
                    .format(len(self.file_definitions)))
            f.write('\n')

            f.write('const FileResourceData g_file_resource_stores[] = {\n')

            for d in self.file_definitions:
                first_resource_id = 'RESOURCE_ID_{}'.format(d['resources'][0])
                last_resource_id = 'RESOURCE_ID_{}'.format(d['resources'][-1])

                # FIXME: We should just get rid of this concept since it's trivially calculated at
                # compile time
                id_offset_expr = '({} - 1)'.format(first_resource_id)

                filename = d['name']

                f.write('  {{ {first}, {last}, {id_offset}, "{filename}" }},\n'
                        .format(first=first_resource_id, last=last_resource_id,
                                id_offset=id_offset_expr, filename=filename))

            f.write("};\n")


@TaskGen.feature('generate_pfs_resources')
@TaskGen.before_method('process_source', 'process_rule')
def generate_pfs_resources(self):
    task = self.create_task('pfs_resources_table',
                            self.resource_definition_files + [self.resource_id_header],
                            self.pfs_table_node)
    task.file_definitions = self.file_definitions
    task.resource_id_header = self.resource_id_header
