#!/usr/bin/env python3
'''functions used by multiple parts of the plugin'''
# -*- encoding: utf-8; py-indent-offset: 4 -*-

# (c) Michael Honkoop <mhonkoop@comsolve.nl>

# License: GNU General Public License v2

import re
import pytz
import datetime
from dateutil import tz

from cmk.agent_based.v2 import (
    DiscoveryResult,
    Service,
)

ignored_items = [
    "IDM jvm_stats",
]

uptime_attributes = [
    "Status_eDirectoryUpTime",
]

time_attributes = [
    "Status_eDirectorySystemCurrTime",
    "CheckPointThreadData_CheckPointThreadStartTime",
]

time_attributes_ignored = [
    "BackGroundProcInterval",
    "CheckPointThreadData_CheckPointThreadForceStartTime",
    "CheckPointThreadData_CheckPointThreadStartTime",
]

non_graphable_attributes = [
    "Status_eDirectorySystemCurrTime",
    "Status_eDirectoryUpTime",
    "Status_eDirectoryAgentVersion",
    "CheckPointThreadData_CheckPointThreadStartTime",
    "CheckPointThreadData_CheckPointThreadForceStartTime",
    "CheckPointThreadData_CheckPointThreadIsForced",
    "Size_CurrentTransactionID",
    "EngineVersion_EngineVersion",
    "driverSet_Stats_driverSetDN",
    "Driver_startOption",
    "Driver_type",
    "Driver_uptime",
    "Driver_driver-state",
    "Driver_DriverDN",
    "Finalizer_lock",
    "Finalizer_state",
    "Dispatcher_state",
    "DirXML_state",
    "Scheduler_lock",
    "Scheduler_state",
    "Scheduler_Id",
    "Handler_lock",
    "Handler_state",
    "IDM jvm_stats",
    "IDM job_stats",
    "system_properties",
]
idm_nongraphable_attributes = [
    "arch",
    "average_load",
    "comitted",
    "configuration",
    "containment",
    "downTime",
    "DriverDN",
    "driver-state",
    "id",
    "initial",
    "JobDN",
    "lock",
    "name",
    "processors",
    "startOption",
    "state",
    "status",
    "total",
    "type",
    "uptime",
    "upTime",
    "used",
    "version",
]

total_counter_attributes = [
    "TrafficVolume_inBytes",
    "TrafficVolume_outBytes",
    "Errors_securityErrors",
    "Errors_errors",
    "Bindings_simpleAuthBinds",
    "Bindings_unAuthBinds",
    "Bindings_bindSecurityErrors",
    "Bindings_strongAuthBinds",
    "IncomingOperations_extendedOps",
    "IncomingOperations_abandonOps",
    "IncomingOperations_wholeSubtreeSearchOps",
    "IncomingOperations_oneLevelSearchOps",
    "IncomingOperations_searchOps",
    "IncomingOperations_listOps",
    "IncomingOperations_modifyRDNOps",
    "IncomingOperations_modifyEntryOps",
    "IncomingOperations_removeEntryOps",
    "IncomingOperations_addEntryOps",
    "IncomingOperations_compareOps",
    "IncomingOperations_readOps",
    "IncomingOperations_inOps",
    "OutgoingOperations_chainings",
    "CacheFaultLooks_Total",
    "CacheFaultLooks_BlockCache",
    "CacheFaultLooks_EntryCache",
    "Hits_Total",
    "Hits_BlockCache",
    "Hits_EntryCache",
    "HitLooks_Total",
    "HitLooks_BlockCache",
    "HitLooks_EntryCache",
    "Thread_Stats_Total_Shared_Count",
]

def format_partition_agent(value):
    """strip unwanted data from Agent Partition data"""
    formatted = re.sub('CN=|OU=|O=|T=', '', value).replace("=", " ").replace(" ", "").split("#")
    return formatted

def format_partition_data(value):
    """strip unwanted data from Agent Partition data"""
    formatted = (re.sub('CN=|OU=|O=', '', value).replace(',', '.')).split("=")
    return formatted

def convert_timestamp(value):
    """convert Zulu time to current time in local timezone"""
    utc_dt = datetime.datetime.strptime(str(value), "%Y%m%d%H%M%SZ")
    utc = pytz.utc
    utc_dt = utc_dt.replace(tzinfo=tz.UTC)
    local_tz = tz.tzlocal()
    local_dt = utc_dt.astimezone(local_tz)
    return local_dt

def parse_ldap_data(string_table):
    """parse one lines of data to dictionary"""
    parsed = {}
    for line in string_table:
        item = line[0]
        parsed.setdefault(item, {})
        for _count, data in enumerate(line[1:]):
            if item == "Agent Partition":
                key, value=format_partition_agent(data)
            else:
                key, value=format_partition_data(data)
            parsed[item].setdefault(key, value)
    return parsed

def discover_edirectory_items(section) -> DiscoveryResult:
    '''discover one item per key'''
    for key, data in section.items():
        '''Yield a Service, unless the key is empty'''
        if len(key) != 0:
            if not key.startswith("IDM jvm_stats"):
                print(key)
                yield Service(item=key)