from .base import BaseCommand
import yaml
from sli.tools import SkilletYamlDumper


class RollupSkillet(BaseCommand):
    sli_command = 'rollup_skillet'
    short_desc = 'Rollup a panos skillet with external XML into a single file'
    no_skillet = True
    no_context = True
    help_text = """

    Usage:
        sli rollup_skillet [skillet-file] [out-file]

"""

    def run(self):
        if not len(self.args) == 2:
            print(self.help_text)
            return

        # Load skillet and copy over non snippet keys
        skillet_file = self.args[0]
        out_file = self.args[1]
        with open(skillet_file, "r") as f:
            skillet = yaml.safe_load(f)
        out_str = yaml.dump(
                {x: y for x, y in skillet.items() if not x == "snippets"},
                Dumper=SkilletYamlDumper,
                sort_keys=False
            )
        out_str += "\nsnippets:\n"

        # Validate supported keys in snippets
        for snippet in skillet["snippets"]:
            for key in snippet.keys():
                if key not in ["name", "xpath", "when", "file"]:
                    print(f"Snippet has unsupported key {key}")
                    return
            for key in ["name", "xpath", "file"]:
                if key not in snippet:
                    print(f"Snippet missing required key {key}")
                    return

        # Generate new skillet with inline XML
        for snippet in skillet["snippets"]:
            out_str += f"\n  - name: {snippet['name']}\n"
            for key, value in {x: y for x, y in snippet.items() if not x == "file" and not x == "name"}.items():
                out_str += f"    {key}: {value}\n"
            with open(snippet["file"], 'r') as f:
                xml_contents = f.read()
                out_str += "    element: |-\n"
                for line in xml_contents.split("\n"):
                    out_str += f"      {line}\n"

        # Generate outfile
        with open(out_file, "w") as f:
            f.write(out_str)
