import os
import posixpath

from parallels.core import safe_format
from parallels.core.utils.file_utils import get_relative_path
from parallels.plesk.source.web import messages


class MigratedFolder(object):
    def __init__(self, global_context, subscription, source_absolute_path, target_relative_path, exclude_paths=None):
        """
        :type global_context: parallels.plesk.source.web.global_context.WebGlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        :type source_absolute_path: str | unicode
        :type target_relative_path: str | unicode
        :type exclude_paths: list[ str | unicode ] | None
        """
        self._global_context = global_context
        self._subscription = subscription
        self._source_absolute_path = source_absolute_path
        self._target_relative_path = target_relative_path.lstrip(os.sep)
        self._exclude_paths = exclude_paths

    def description(self):
        """
        :rtype: str | unicode
        """
        return safe_format(
            messages.FOLDER_DESCRIPTION, path=self.source_path
        )

    @property
    def target_subscription_name(self):
        """
        :rtype: str | unicode
        """
        return self._subscription.name

    @property
    def source_path(self):
        """
        :rtype: str | unicode
        """
        server = self._global_context.conn.get_source()

        source_relative_path = posixpath.join(
            '/',
            get_relative_path(
                self.source_absolute_path, server.get_absolute_filesystem_root_path(),
                False, server.is_windows(), server.is_windows()
            )
        )
        return source_relative_path

    @property
    def source_absolute_path(self):
        """
        :rtype: str | unicode
        """
        return self._source_absolute_path

    @property
    def target_path(self):
        """
        :rtype: str | unicode
        """
        document_root = self._global_context.site_info_storage.get_target_document_root()
        return os.path.join(document_root, self._target_relative_path)

    @property
    def target_relative_path(self):
        """
        :rtype: str | unicode
        """
        return self._target_relative_path

    @property
    def target_server(self):
        """
        :rtype: parallels.core.connections.target_servers.PleskTargetServer | None
        """
        return self._global_context.conn.target.plesk_server

    @property
    def target_sysuser_login(self):
        """
        :rtype: str | unicode
        """
        return self._global_context.site_info_storage.get_target_sysuser_login()

    @property
    def path_excludes(self):
        """
        :rtype: list[ str | unicode ]
        """
        return self._exclude_paths if self._exclude_paths is not None else []
