# SPDX-License-Identifier: Apache-2.0
# Copyright 2022 EPAM Systems
"""
Archive packer builder module
"""

import os.path
from typing import List
from moulin.yaml_wrapper import YamlValue
from moulin import ninja_syntax


def get_builder(conf: YamlValue, name: str, build_dir: str, src_stamps: List[str],
                generator: ninja_syntax.Writer):
    """
    Return configured ArchiveBuilder class
    """
    return ArchiveBuilder(conf, name, build_dir, src_stamps, generator)


def gen_build_rules(generator: ninja_syntax.Writer):
    """
    Generate yocto build rules for ninja
    """

    generator.rule("tar_pack",
                   "tar --sparse --dereference --create --auto-compress --file=$out $items",
                   description="Archiving into $out",
                   restat=True)
    generator.newline()


class ArchiveBuilder:
    """
    ArchiveBuilder class generates Ninja rules to archive files
    """

    def __init__(self, conf: YamlValue, name: str, build_dir: str, src_stamps: List[str],
                 generator: ninja_syntax.Writer):
        self.conf = conf
        self.name = name
        self.generator = generator
        self.src_stamps = src_stamps
        self.build_dir = build_dir

    def gen_build(self):
        """Generate ninja rules to create archive"""
        items = [x.as_str for x in self.conf["items"]]

        targets = self.get_targets()
        deps = list(self.src_stamps)
        deps.extend(items)

        self.generator.build(targets, "tar_pack", deps, variables={"items": items})
        self.generator.newline()

        return targets

    def get_targets(self):
        "Return list of targets that are generated by this build"
        return [os.path.join(self.build_dir, self.conf["name"].as_str)]

    def capture_state(self):
        """
        This method should capture state for reproducible builds.
        Luckily, there is nothing to do, as this builder just arhives
        existing files
        """
