import posixpath

from parallels.core.utils.paths import web_paths
from parallels.core.utils.paths.copy_web_content import CopyWebContentItem
from parallels.core.utils.paths.web_files import BaseWebFiles


class CpanelWebFiles(BaseWebFiles):
    """List web files and directories to be copied from custom panel"""

    def list_files_to_copy(self, global_context, subscription):
        """Make a list of source server directories and files to be transferred.

        :type global_context: parallels.plesk.source.cpanel.global_context.CpanelGlobalMigrationContext
        :type subscription: parallels.plesk.source.cpanel.migrated_subscription.CPanelMigratedSubscription
        :rtype: list[parallels.core.utils.paths.copy_web_content.CopyWebContentItem]
        """
        sysuser = subscription.raw_dump.get_phosting_sysuser_name()

        document_root_excludes = ['/mail', '/.*']

        is_subscription_www_root_defined = (
            subscription.raw_dump.is_virtual_hosting and subscription.raw_dump.www_root is not None
        )

        if is_subscription_www_root_defined:
            document_root_excludes.append('/%s' % subscription.raw_dump.www_root)

        files = [
            CopyWebContentItem(
                source_path=web_paths.AbsolutePath(subscription.source_home_dir),
                target_path=web_paths.WebspaceRoot(subscription.converted_dump),
                exclude=document_root_excludes,
            ),
            # Unprocessed logs
            CopyWebContentItem(
                source_path=web_paths.AbsolutePath(posixpath.join('/usr/local/apache/domlogs', sysuser) + '/'),
                target_path=web_paths.WebspacePathTemplate(
                    subscription.converted_dump, "{webspace_root}/cpanel_raw_logs/"
                ),
                skip_if_source_not_exists=True,
                fix_application_paths=False
            )
        ]

        if is_subscription_www_root_defined:
            files.append(
                CopyWebContentItem(
                    source_path=web_paths.AbsolutePath(
                        posixpath.join(subscription.source_home_dir, subscription.raw_dump.www_root)
                    ),
                    target_path=web_paths.WebspaceDocumentRoot(subscription.converted_dump),
                )
            )

        return files
