import sys
from rich.console import Console
import os
import time
from time import sleep
import requests
import urllib3
import json
from deepsecurity.rest import ApiException
from dsmigrator.api_config import AMConfigApiInstance
from dsmigrator.migrator_utils import validate_create, validate_create_dict

console = Console()


cert = False


def am_config_transform(antimalwareconfig, OLD_HOST, OLD_API_KEY):
    amdirectorylist, amfileextentionlist, amfilelist, allamconfig = AMconfigtenant1(
        antimalwareconfig, OLD_HOST, OLD_API_KEY
    )
    return amdirectorylist, amfileextentionlist, amfilelist, allamconfig


def am_validate_create(
    allofpolicy,
    antimalwareconfig,
    allamconfig,
    amdirectorylist,
    amalldirectorynew,
    amfileextentionlist,
    amallfileextentionnew,
    amfilelist,
    amallfilelistnew,
    NEW_HOST,
    NEW_API_KEY,
):
    mod_allamconfig = AmConfigCheck(
        allamconfig,
        amdirectorylist,
        amalldirectorynew,
        amfileextentionlist,
        amallfileextentionnew,
        amfilelist,
        amallfilelistnew,
    )

    # renamed_allamconfig = RenameAmConfig(mod_allamconfig)

    allamconfigdict = AmconfigTenant2(mod_allamconfig, NEW_API_KEY)

    aop_replace_am_configs = AmReplaceConfig(allofpolicy, allamconfigdict)
    final = aop_replace_am_configs
    return final


def json_to_list(json_item, key, outlist):
    item = json_item.get(key)
    if item:
        outlist.append(str(item))
        return outlist


def AMconfigtenant1(antimalwareconfig, url_link_final, tenant1key):
    allamconfig = []
    directorylist = []
    fileextentionlist = []
    filelist = []
    print("Getting Anti-Malware configuration from Tenant 1", flush=True)
    for count, amconfig in enumerate(antimalwareconfig):
        if int(amconfig) != 0:
            payload = {}
            url = url_link_final + "api/antimalwareconfigurations/" + str(amconfig)
            headers = {
                "api-secret-key": tenant1key,
                "api-version": "v1",
                "Content-Type": "application/json",
            }
            response = requests.request(
                "GET", url, headers=headers, data=payload, verify=cert
            )

            describe = str(response.text)
            allamconfig.append(describe)
            describe_json = json.loads(describe)
            json_to_list(describe_json, "directoryListID", directorylist)
            json_to_list(describe_json, "excludedDirectoryListID", directorylist)
            json_to_list(
                describe_json, "excludedFileExtensionListID", fileextentionlist
            )
            json_to_list(describe_json, "fileExtensionListID", fileextentionlist)
            json_to_list(describe_json, "excludedFileListID", filelist)
            json_to_list(describe_json, "fileListID", filelist)
            json_to_list(describe_json, "excludedProcessImageFileListID", filelist)
            print(
                "#" + str(count) + " Anti-Malware Config ID: " + str(amconfig),
                flush=True,
            )
    directorylist = list(dict.fromkeys(directorylist))
    fileextentionlist = list(dict.fromkeys(fileextentionlist))
    filelist = list(dict.fromkeys(filelist))
    return directorylist, fileextentionlist, filelist, allamconfig


def AmconfigTenant2(allamconfig, NEW_API_KEY):
    print("Creating Anti-Malware Configuration in Tenant2", flush=True)
    if allamconfig:
        allamconfigdict = validate_create_dict(
            allamconfig, AMConfigApiInstance(NEW_API_KEY), "anti malware"
        )
    print("New AM Config Dict", flush=True)
    print(allamconfigdict, flush=True)
    allamconfigdict[0] = 0
    return allamconfigdict


def AmReplaceConfig(allofpolicy, allamconfigdict):

    count = 0
    for describe in allofpolicy:

        def replace_am_id(
            type,
            policy_json_string,
            newiddict=allamconfigdict,
        ):
            policy_json = json.loads(policy_json_string)
            policy_am_json = policy_json["antiMalware"]
            oldid = policy_am_json[type]
            policy_am_json[type] = newiddict[oldid]
            final_json = json.dumps(policy_json)
            return final_json

        describe_rt = replace_am_id("realTimeScanConfigurationID", describe)
        describe_man = replace_am_id("manualScanConfigurationID", describe_rt)
        describe_sch = replace_am_id("scheduledScanConfigurationID", describe_man)

        allofpolicy[count] = describe_sch
        count = count + 1
    return allofpolicy


def AmConfigCheck(
    allamconfig,
    directorylist,
    alldirectorynew,
    fileextentionlist,
    allfileextentionnew,
    filelist,
    allfilelistnew,
):

    count = 0
    for describe in allamconfig:
        count1 = 0
        index = describe.find('"directoryListID"')
        if index != -1:
            indexpart = describe[index + 17 :]
            startIndex = indexpart.find(":")
            if startIndex != -1:  # i.e. if the first quote was found
                endIndex = indexpart.find(",", startIndex + 1)
                if startIndex != -1 and endIndex != -1:  # i.e. both quotes were found
                    indexid = indexpart[startIndex + 1 : endIndex]
                    for dirlist in directorylist:
                        if indexid == dirlist:
                            if alldirectorynew:
                                describe = (
                                    describe[: index + 17 + startIndex + 1]
                                    + alldirectorynew[count1]
                                    + describe[index + 17 + startIndex + endIndex :]
                                )
                        count1 = count1 + 1
        count1 = 0
        index = describe.find("excludedDirectoryListID")
        if index != -1:
            indexpart = describe[index + 24 :]
            startIndex = indexpart.find(":")
            if startIndex != -1:  # i.e. if the first quote was found
                endIndex = indexpart.find(",", startIndex + 1)
                if startIndex != -1 and endIndex != -1:  # i.e. both quotes were found
                    indexid = indexpart[startIndex + 1 : endIndex]
                    for dirlist in directorylist:
                        if indexid == dirlist:
                            if alldirectorynew:
                                describe = (
                                    describe[: index + 24 + startIndex + 1]
                                    + alldirectorynew[count1]
                                    + describe[index + 24 + startIndex + endIndex :]
                                )
                        count1 = count1 + 1
        count1 = 0
        index = describe.find("excludedFileExtensionListID")
        if index != -1:
            indexpart = describe[index + 28 :]
            startIndex = indexpart.find(":")
            if startIndex != -1:  # i.e. if the first quote was found
                endIndex = indexpart.find(",", startIndex + 1)
                if startIndex != -1 and endIndex != -1:  # i.e. both quotes were found
                    indexid = indexpart[startIndex + 1 : endIndex]
                    for dirlist in fileextentionlist:
                        if indexid == dirlist:
                            if allfileextentionnew:
                                describe = (
                                    describe[: index + 28 + startIndex + 1]
                                    + allfileextentionnew[count1]
                                    + describe[index + 28 + startIndex + endIndex :]
                                )
                        count1 = count1 + 1
        count1 = 0
        index = describe.find('"fileExtensionListID"')
        if index != -1:
            indexpart = describe[index + 21]
            startIndex = indexpart.find(":")
            if startIndex != -1:  # i.e. if the first quote was found
                endIndex = indexpart.find(",", startIndex + 1)
                if startIndex != -1 and endIndex != -1:  # i.e. both quotes were found
                    indexid = indexpart[startIndex + 1 : endIndex]
                    for dirlist in fileextentionlist:
                        if indexid == dirlist:
                            if allfileextentionnew:
                                describe = (
                                    describe[: index + 21 + startIndex + 1]
                                    + allfileextentionnew[count1]
                                    + describe[index + 21 + startIndex + endIndex :]
                                )
                        count1 = count1 + 1
        count1 = 0
        index = describe.find("excludedFileListID")
        if index != -1:
            indexpart = describe[index + 19 :]
            startIndex = indexpart.find(":")
            if startIndex != -1:  # i.e. if the first quote was found
                endIndex = indexpart.find(",", startIndex + 1)
                if startIndex != -1 and endIndex != -1:  # i.e. both quotes were found
                    indexid = indexpart[startIndex + 1 : endIndex]
                    for dirlist in filelist:
                        if indexid == dirlist:
                            if allfilelistnew:
                                describe = (
                                    describe[: index + 19 + startIndex + 1]
                                    + allfilelistnew[count1]
                                    + describe[index + 19 + startIndex + endIndex :]
                                )
                        count1 = count1 + 1
        count1 = 0
        index = describe.find("excludedProcessImageFileListID")
        if index != -1:
            indexpart = describe[index + 31 :]
            startIndex = indexpart.find(":")
            if startIndex != -1:  # i.e. if the first quote was found
                endIndex = indexpart.find(",", startIndex + 1)
                if startIndex != -1 and endIndex != -1:  # i.e. both quotes were found
                    indexid = indexpart[startIndex + 1 : endIndex]
                    for dirlist in filelist:
                        if indexid == dirlist:
                            if allfilelistnew:
                                describe = (
                                    describe[: index + 31 + startIndex + 1]
                                    + allfilelistnew[count1]
                                    + describe[index + 31 + startIndex + endIndex :]
                                )
                        count1 = count1 + 1
        allamconfig[count] = describe
        count = count + 1
        # console.print(f"CONFIGCHECKALLAMCONFIG:\n{allamconfig}", style="bold red")
    return allamconfig


def RenameAmConfig(allamconfig):
    count = 0
    if allamconfig:
        for describe in allamconfig:
            amjson = json.loads(describe)
            print(describe)
            amjson["name"] = amjson["name"] + " - Migrated"
            allamconfig[count] = json.dumps(amjson)
            count = count + 1
    # console.print(f"RENAMEALLAMCONFIG:\n{allamconfig}", style="bold red")
    return allamconfig
