import re

from parallels.core import messages
from parallels.core.actions.base.subscription_action import SubscriptionAction
from parallels.core.actions.hosting_settings.detect_scripting.utils import (
    upload_probe, list_domains_to_detect_scripting
)
from parallels.core.dump.data_model import Scripting
from parallels.core.logging import get_logger
from parallels.core.migrator_config import read_detect_scripting_settings_enabled
from parallels.core.utils.http_client import perform_simple_http_request

logger = get_logger(__name__)


class DetectASPNETVersionAction(SubscriptionAction):
    def get_description(self):
        """Get short description of action as string

        :rtype: str | unicode
        """
        return messages.DETECT_ASP_NET_VERSION_ACTION_DESCRIPTION

    def get_failure_message(self, global_context, subscription):
        """Get message for situation when action failed

        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        :rtype: str | unicode
        """
        return messages.DETECT_ASP_NET_VERSION_ACTION_FAILURE

    def filter_subscription(self, global_context, subscription):
        """Check if we should run this action on given subscription or not

        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        :rtype: bool
        """
        return (
            read_detect_scripting_settings_enabled(global_context.config) and
            subscription.web_source_server.is_windows()
        )

    def is_critical(self):
        """If action is critical or not

        :rtype: bool
        """
        return False

    def run(self, global_context, subscription):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        """
        domains_to_detect_scripting = list_domains_to_detect_scripting(global_context, subscription)
        for domain, source_document_root, source_domain_ip in domains_to_detect_scripting:
            self._update_asp_net_version(subscription, domain, source_document_root, source_domain_ip)

    def _update_asp_net_version(self, subscription, domain, source_document_root, source_domain_ip):
        """Detect ASP.NET version and update it in dump

        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        :type domain: parallels.core.dump.data_model.Domain
        :type source_document_root: str | unicode
        :type source_domain_ip: str | unicode
        """
        if domain.scripting is None:
            return

        asp_dot_net_version = self._detect_asp_net_version(
            subscription, domain, source_document_root, source_domain_ip
        )
        if asp_dot_net_version is None:
            return

        domain.scripting.enable_option(Scripting.OPTION_ASP_DOT_NET)
        if asp_dot_net_version == "2":
            version_option_value = Scripting.VALUE_ASP_DOT_NET_VERSION_2_0
        else:
            version_option_value = Scripting.VALUE_ASP_DOT_NET_VERSION_4_0
        domain.scripting.set_option(Scripting.OPTION_ASP_DOT_NET_VERSION, version_option_value)

    @staticmethod
    def _detect_asp_net_version(subscription, domain, source_document_root, source_domain_ip):
        """Detect ASP.NET version by uploading probe script

        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        :type domain: parallels.core.dump.data_model.Domain
        :type source_document_root: str | unicode
        :type source_domain_ip: str | unicode
        :rtype: str | unicode
        """
        asp_dot_net_script_contents = '<% Response.Write("VERSION=" + System.Environment.Version.ToString()) %>'

        with upload_probe(
                subscription.web_source_server, source_document_root, "aspx", asp_dot_net_script_contents
        ) as temp_script_name:
            body = perform_simple_http_request(source_domain_ip, domain.name_idn, temp_script_name)
            match = re.match(r"^VERSION=(\d+)\..*$", body)

            if match is None:
                return None

            asp_dot_net_version = match.group(1)
            logger.fdebug(
                messages.DETECTED_ASP_DOT_NET_VERSION, site=domain.name, version=asp_dot_net_version
            )

            return asp_dot_net_version
