import os

import parallels
from parallels.core import get_logger
from parallels.core.runners.base import BaseRunner
from parallels.core.runners.entities import ControlledInterruption, ExecutionOptions
from parallels.core.utils.migrator_utils import get_package_extras_file_path
from parallels.plesk.source.web.utils.copy_content.base import CopyContentBase
from parallels.plesk.source.web.utils.copy_content.web_streaming_utils import create_config, parse_output

logger = get_logger(__name__)


class CopyContentLinuxWebStreaming(CopyContentBase):
    def copy_folder(self, global_context, folder):
        """Run action for single migrated folder

        :type global_context: parallels.plesk.source.web.global_context.WebGlobalMigrationContext
        :type folder: parallels.plesk.source.web.migrated_folder.MigratedFolder
        :rtype: list[parallels.core.reports.model.issue.Issue] | None
        """
        config_json = create_config(global_context, folder)

        web_stream_downloader_path = get_package_extras_file_path(parallels.core, "web-stream-downloader")
        web_stream_downloader_executable = os.path.join(web_stream_downloader_path, 'web-stream-downloader')
        controlled_interruption = ControlledInterruption(stop_mark=global_context.stop_mark)

        with folder.target_server.runner() as local_runner:
            assert isinstance(local_runner, BaseRunner)

            command_results = local_runner.execute_command(
                u'su {username} --shell /bin/sh -c {command}', dict(
                    username=folder.target_sysuser_login,
                    command=u"{web_stream_downloader_executable} --config-file -".format(
                        web_stream_downloader_executable=web_stream_downloader_executable
                    )
                ),
                ExecutionOptions(
                    stdin_content=config_json,
                    umask=0o22,
                    controlled_interruption=controlled_interruption
                )
            )

        return parse_output(command_results.stdout, command_results.stderr)
