import logging
import os.path

from sandbox import sdk2


class SandboxWithArcadiaDownload(sdk2.Task):
    def on_execute(self):
        from load.tools.yaml_injection import InjectionLoader
        from load.tools.yaml_injection.resource_loader import BaseResourceLoader
        from sandbox.sdk2.vcs.svn import Arcadia
        import tempfile
        import yaml

        class SandboxArcadiaLoader(BaseResourceLoader):
            def key(self):
                return 'arcadia'

            def download_resource(self, arc_path):
                file = os.path.join(tempfile.gettempdir(), next(tempfile._get_candidate_names()))
                try:
                    Arcadia.export(Arcadia.trunk_url(arc_path), file, depth='empty')
                    with open(file, 'r') as config:
                        read = config.read()
                        logging.info("Downloaded from arcadia: ")
                        logging.info(read)
                        return read
                finally:
                    os.remove(file)

        MAIN_YAML = """
!inject arcadia: load/projects/cloud/tank_client/config/config.yaml

load_testing_port: 123
        """

        logging.info('Use as main.yaml:')
        logging.info(MAIN_YAML)

        loaded_data = yaml.load(MAIN_YAML, InjectionLoader.with_resources(SandboxArcadiaLoader()))

        self.loaded = yaml.dump(loaded_data)
        logging.info("loaded:")
        logging.info(self.loaded)

    @sdk2.header(title="Скачалось:")
    def header(self):
        return self.loaded
