import os

from parallels.core.runners.base import BaseRunner
from parallels.core.runners.entities import ControlledInterruption, ExecutionOptions
from parallels.core.utils.common import is_empty
from parallels.plesk.source.web.utils.copy_content.base import CopyContentBase
from parallels.plesk.source.web.utils.copy_content.ftp_migrator_utils import create_config, parse_output
from parallels.plesk.source.web.utils.copy_content.windows_utils import parse_php_wrapper_output


class CopyContentWindowsFTP(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
        """
        source = global_context.conn.get_source()
        config_json = create_config(source, folder)

        controlled_interruption = ControlledInterruption(stop_mark=global_context.stop_mark)

        # Call wrapper around the FTP migrator, which executes the FTP migrator under specified user
        extension_id = os.getenv('PLESK_EXTENSION_ID')
        if is_empty(extension_id):
            extension_id = 'panel-migrator'

        with folder.target_server.runner() as local_runner:
            assert isinstance(local_runner, BaseRunner)
            command_results = local_runner.execute_command(
                u'plesk bin extension --exec {extension_id} ftp-migrator.php {user}',
                dict(extension_id=extension_id, user=folder.target_sysuser_login),
                ExecutionOptions(
                    stdin_content=config_json,
                    controlled_interruption=controlled_interruption
                )
            )

        stdout, stderr = parse_php_wrapper_output(command_results)
        return parse_output(stdout, stderr)
