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
from parallels.core.utils.migrator_utils import version_to_tuple

logger = get_logger(__name__)


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

        :rtype: str | unicode
        """
        return messages.DETECT_PHP_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_PHP_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_php_version(subscription, domain, source_document_root, source_domain_ip)

    def _update_php_version(self, subscription, domain, source_document_root, source_domain_ip):
        """Detect PHP version and SAPI name 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

        php_version, php_sapi = self._detect_php_version(
            subscription, domain, source_document_root, source_domain_ip
        )
        if php_version is None:
            return

        if php_sapi == "isapi":
            php_handler_type_option_value = Scripting.VALUE_PHP_HANDLER_TYPE_ISAPI
        elif php_sapi == "cgi":
            php_handler_type_option_value = Scripting.VALUE_PHP_HANDLER_TYPE_CGI
        elif php_sapi == "fpm-fcgi":
            php_handler_type_option_value = Scripting.VALUE_PHP_HANDLER_TYPE_FPM
        elif php_sapi.startswith("apache"):
            php_handler_type_option_value = Scripting.VALUE_PHP_HANDLER_TYPE_MODULE
        else:
            php_handler_type_option_value = Scripting.VALUE_PHP_HANDLER_TYPE_FASTCGI

        if version_to_tuple(php_version) < (5, 0):
            php_version_option_value = Scripting.VALUE_PHP_VERSION_4_x
        elif version_to_tuple(php_version) < (5, 3):
            php_version_option_value = Scripting.VALUE_PHP_VERSION_5_BELOW_5_3
        else:
            php_version_option_value = php_version

        domain.scripting.enable_option(Scripting.OPTION_PHP)
        domain.scripting.set_option(Scripting.OPTION_PHP_HANDLER_TYPE, php_handler_type_option_value)
        domain.scripting.set_option(Scripting.OPTION_PHP_VERSION, php_version_option_value)

    @staticmethod
    def _detect_php_version(subscription, domain, source_document_root, source_domain_ip):
        """Detect PHP version and SAPI name 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: tuple
        """
        php_script_contents = '<?php echo "VERSION=" . phpversion() . ";SAPI=" . php_sapi_name();'

        with upload_probe(
            subscription.web_source_server, source_document_root, "php", php_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+\.\d+).*;SAPI=(.*)$", body)
            if match is None:
                return None, None

            php_version = match.group(1)
            php_sapi = match.group(2)

            logger.fdebug(messages.DETECTED_PHP_VERSION, site=domain.name, version=php_version, sapi=php_sapi)
            return php_version, php_sapi
