# -*- coding: utf-8 -*-

# Copyright 2016 Mir Calculate. http://www.calculate-linux.org
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import sys
from calculate.core.server.func import Action, Tasks
from calculate.lib.cl_lang import setLocalTranslate, getLazyLocalTranslate
from calculate.lib.cl_template import TemplatesError
from calculate.lib.utils.files import FilesError
from calculate.lib.datavars import VariableError
from calculate.server.variables.action import Actions
from ..ldap import LdapError, Ldap
from calculate.server.server import ServerError

_ = lambda x: x
setLocalTranslate('cl_ldap3', sys.modules[__name__])
__ = getLazyLocalTranslate(_)


class MetaTasks(object):
    def __init__(self, obj):
        self.obj = obj

    def ldif_task(self, ldap_params, action):
        return [
            {'name': 'set_ldif',
             'method': '%s.set_ldap_connection(%s)' % (self.obj, ldap_params)
             },
            {'name': 'ldif_action',
             'method': '%s.set_server_action("%s")' % (self.obj, Actions.Ldif),
             },
            {'name': 'ldif',
             'method': '%s.applyTemplates(install.cl_source,'
                       'False,True,None,False,True)' % self.obj,
             },
            {'name': 'ldif_action',
             'method': '%s.set_server_action("%s")' % (self.obj, action),
             },
        ]


class ClLdapSetupAction(Action):
    """
    Действие обновление конфигурационных файлов
    """
    # ошибки, которые отображаются без подробностей
    native_error = (FilesError,
                    TemplatesError,
                    VariableError,
                    ServerError,
                    LdapError)

    successMessage = None
    failedMessage = __("Failed to configure LDAP server!")
    interruptMessage = __("LDAP configuration manually interrupted")

    meta_tasks = MetaTasks("Ldap")

    # список задач для удаления сервера
    uninstall_tasks = [
        {'name': 'clear_creds',
         'method': 'Server.clear_service_data("all")',
         #'condition': lambda Get: Get('server.sr_ldap_set') == 'on'
         },
        {'name': 'unset_ldap',
         'method': 'Server.service_uninstall("ldap")',
         'condition': lambda Get: Get('server.sr_ldap_set') == 'on'
         },
    ]

    stop_tasks = [
        {'name': 'noautorun',
         'method': 'Server.autorun_disable("%s")' % Ldap.Service.LDAP,
         },
        {'name': 'stop_slapd',
         'message': __("Stopping LDAP service"),
         'method': 'Server.stop_service("%s")' % Ldap.Service.LDAP,
         },
    ]

    # список задач для конфигурирования сервера
    configure_task = [

    ]

    # список задач для действия
    tasks = [
        {'name': 'remove_service',
         'condition': lambda Get: (Get('cl_ldap_remove_set') == 'on' or
                                   Get('server.sr_ldap_set') != 'on')
         },
        {'name': 'remove_only',
         'message': _("Removing LDAP service"),
         'condition': lambda Get: (Get('cl_ldap_remove_set') == 'on' and
                                   Get('server.sr_ldap_set') == 'on')
         },
        {'name': 'password_generation',
         'condition': lambda Get: Get('cl_ldap_pw_generate_set') == 'on'
         },
        {'name': 'setup_service',
         'condition': lambda Get: Get('server.sr_ldap_set') != 'on'
         },
        {'name': 'remove_service:uninstall',
         'tasks': uninstall_tasks,
         },
        {'name': 'remove_service:stop',
         'tasks': stop_tasks,
         },
        {'name': 'preconfigure',
         'message': __("Pre-configure LDAP"),
         'method': 'Ldap.preconfigureTemplates()',
         'condition': lambda Get: (Get('cl_ldap_remove_set') != 'on' or
                                   Get('cl_ldap_remove_set') != 'on'),
         'depend': Tasks.success() & Tasks.has_any("password_generation",
                                                    "setup_service")
         },
        {'name': 'remove_service:remove_old_db',
         'method': 'Ldap.remove_ldap_db(ld_database_path)'
         },
        {'name': 'password_generation:restart_slapd',
         'message': __("Restarting LDAP service"),
         'method': 'Server.restart_service("%s")' % Ldap.Service.LDAP,
         },
        {'name': 'setup_service:start_slapd',
         'message': __("Starting LDAP service"),
         'method': 'Server.start_service("%s")' % Ldap.Service.LDAP,
         'condition': lambda Get: Get('cl_ldap_remove_set') != 'on'
         },
        {'name': 'setup_service:apply_ldif',
         'tasks': meta_tasks.ldif_task("ld_temp_dn,ld_temp_pw", Actions.Setup)
         },
        {'name': 'password_generation:set_ldif',
         'method': 'Ldap.set_ldap_connection(ld_temp_dn,ld_temp_pw)'
         },
        {'name': 'password_generation:gen_pass',
         'message': _("Create new LDAP service password"),
         'method': 'Ldap.generate_password(ld_admin_dn,ld_admin_hash,"LDAP")',
         'condition': lambda Get: Get('cl_ldap_pw_generate_set') == 'on'
         },
        {'name': 'templates',
         'message': __("Configure system"),
         'method': 'Server.applyTemplates(install.cl_source,'
                   'False,True,None,True,True)',
         },
        {'name': 'restart_slapd',
         'message': __("Restarting LDAP service"),
         'method': 'Server.restart_service("%s")' % Ldap.Service.LDAP,
         'condition': lambda Get: Get('cl_ldap_remove_set') != 'on',
         },
        {'name': 'save_creds',
         'method': 'Server.save_service_data("admin",ld_admin_dn,ld_admin_pw)',
         'depend': Tasks.success() & Tasks.has_any("password_generation",
                                                   "setup_service")
         },
        {'name': 'setup_service:autorun',
         'method': 'Server.autorun_enable("%s")' % Ldap.Service.LDAP,
         },
        {'name': 'setup_service:save_data',
         'method': 'Ldap.save_variables()',
         },
        {'name': 'setup_service:set_ldap',
         'method': 'Server.service_install("ldap")',
         },
        {'name': 'success',
         'message': __("LDAP server configured!"),
         'condition': lambda Get: Get('cl_ldap_remove_set') != 'on',
         'depend': (Tasks.success() & Tasks.hasnot("failed"))
         },
        {'name': 'success',
         'message': __("LDAP server removed!"),
         'condition': lambda Get: Get('cl_ldap_remove_set') == 'on',
         'depend': (Tasks.success() & Tasks.hasnot("failed"))
         }
    ]

    @classmethod
    def register_stop(cls, stop_tasks):
        cls.stop_tasks.extend(stop_tasks)

    @classmethod
    def register_uninstall(cls, uninstall_tasks):
        cls.uninstall_tasks.extend(uninstall_tasks)
