# Copyright 2021-2025 Ping Identity Corporation. All Rights Reserved
#
# This code is to be used exclusively in connection with Ping Identity
# Corporation software or services. Ping Identity Corporation only offers
# such software or services to legal entities who have entered into a
# binding license agreement with Ping Identity Corporation.

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

# load tasks used by configuration file

# Framework imports
from pyrock.lib.scheduler.tasks.StepTask import StepTask
from pyrock.lib.scheduler.tasks.OverseerTask import OverseerTask
from pyrock.tasks.scenario.ds_sdk import (
    DSModRateTask,
    DSLdapModifyTask,
    ResetPolicies,
    GenerateLdifTask,
    GenerateDSAddRateTemplateTask,
)
from shared.lib.cloud_utils import kubectl
from shared.lib.utils.exception import FailException


class CreateIndexTask(StepTask):
    pod = None
    index_name = None
    index_type = None
    extensible_matching_rule = None
    big_index_matching_rule = None

    def connection_parameters(self):
        cmd = [
            f"--hostname {self.pod.name}",
            f"--port {self.pod.component.admin_port}",
            f"--bindDN {self.pod.component.admin_user}",
            f"--bindPassword {self.pod.component.admin_password}",
            self.pod.component.default_props_line,
            f"--no-prompt",
        ]
        return " ".join(cmd)

    def pre(self):
        if not self.source.component_type == "ds":
            raise FailException("Source must be ds component")
        self.pod = self.source.pods[0]

    def step1(self):
        """Delete index"""
        cmd = "dsconfig delete-backend-index "
        cmd += f"--backend-name {self.pod.component.backend_id} --index-name {self.index_name} "
        cmd += self.connection_parameters()

        kubectl(
            f"exec {self.pod.name} -- {cmd}",
            namespace=self.source.namespace,
            expected_rc=[0, 32],
            component=self.source,
        )

    def step2(self):
        """Add index"""
        cmd = "dsconfig create-backend-index "
        cmd += f"--backend-name {self.pod.component.backend_id} --type generic "
        cmd += f"--index-name {self.index_name} --set index-type:{self.index_type} "
        cmd += self.connection_parameters()

        kubectl(f"exec {self.pod.name} -- {cmd}", namespace=self.source.namespace, component=self.source)

    def step3(self):
        """Rebuild index"""
        cmd = f"rebuild-index --baseDn {self.pod.component.base_dn} --index {self.index_name} "
        cmd += self.connection_parameters()

        kubectl(f"exec {self.pod.name} -- {cmd}", namespace=self.source.namespace, max_time=1800, component=self.source)


class CreateSubstringIndexTask(CreateIndexTask):
    index_name = "description"
    index_type = "substring"
