#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# coding: utf8
import json
import json5
import urllib.request
import os
import copy
import re

from ffxiv_aku import *
from ffxiv_aku import writeJsonFile

items = None
items = None

DoH = ["ZMR", "GRS", "PLA", "GLD", "GER", "WEB", "ALC", "GRM"]
DoL = ["MIN", "GÄR", "FIS"]
TANKS = ["GLA", "PLD", "MAR", "KRG", "DKR", "REV"]
HEALER = ["DRU", "WMA", "GLT", "AST", "WEI"]
MELEE = ["FST", "MÖN", "PIK", "DRG", "SCH", "NIN", "SAM", "SNT", "VPR"]
CASTER = ["THM", "SMA", "HRT", "BSW", "RMA", "BMA", "PKT"]
PHYS_RANGED = ["WDL", "BRD", "MCH", "TÄN"]
DoW = TANKS + MELEE + PHYS_RANGED
DoM = CASTER + HEALER
KAMPFKLASSEN = DoM + DoW
CLASS_JOB_CATEGORY = ["Krieger", "Magier", "Sammler", "Handwerker", "Alle"] + DoL + DoH + DoM + DoW

def checkItemIsValid(item):
    for c in item["ClassJobCategory"]['Name_de'].split(" "):
        if c == "":  # in CLASS_JOB_CATEGORY
            return False
    return item["Name_de"] != ""


def handleStats(x_item, item):
    x_item["Stats"] = {}
    for c in item["ClassJobCategory"]['Name_de'].split(" "):
        if c in DoH:
            x_item["Stats"]["Kunstfertigkeit"] = 0
            x_item["Stats"]["Kontrolle"] = 0
            x_item["Stats"]["HP"] = 0
        if c in DoL:
            x_item["Stats"]["Sammelgeschick"] = 0
            x_item["Stats"]["Wahrnehmung"] = 0
            x_item["Stats"]["SP"] = 0
        if c in DoM:
            x_item["Stats"]["Mag. Basiswert"] = int(item["DamageMag"])
            x_item["Stats"]["Verteidigung"] = int(item["DefensePhys"])
            x_item["Stats"]["Magieabwehr"] = int(item["DefenseMag"])
            x_item["Stats"]["Zaubertempo"] = 0
        if c in DoW:
            x_item["Stats"]["Phys. Basiswert"] = int(item["DamagePhys"])
            x_item["Stats"]["Verteidigung"] = int(item["DefensePhys"])
            x_item["Stats"]["Magieabwehr"] = int(item["DefenseMag"])
            x_item["Stats"]["Schnelligkeit"] = 0
        if c in PHYS_RANGED:
            x_item["Stats"]["Geschick"] = 0
            x_item["Stats"]["Schnelligkeit"] = 0
        if c in TANKS:
            if c in ["GLA", "PLD"]:
                x_item["Stats"]["Blockeffekt"] = int(item["Block"])
                x_item["Stats"]["Blockrate"] = int(item["BlockRate"])
            x_item["Stats"]["Stärke"] = 0
            x_item["Stats"]["Schnelligkeit"] = 0
            x_item["Stats"]["Unbeugsamkeit"] = 0
        if c in HEALER:
            x_item["Stats"]["Willenskraft"] = 0
            x_item["Stats"]["Frömmigkeit"] = 0
        if c in CASTER:
            x_item["Stats"]["Intelligenz"] = 0
        if c in MELEE:
            x_item["Stats"]["Stärke"] = 0
        if c in KAMPFKLASSEN:
            x_item["Stats"]["Direkter Treffer"] = 0
            x_item["Stats"]["Kritischer Treffer"] = 0
            x_item["Stats"]["Entschlossenheit"] = 0
            x_item["Stats"]["Konstitution"] = 0

    for x in range(0, 6):
        try:
            x_item["Stats"][item["BaseParam"][x]['Name_de']] = int(item["BaseParamValue"][x])
        except Exception:
            print("ERROR")
            sdf
            pass
    return x_item


def getHQItemsPath(hq_x_item_y):
    hq_x_item_array = hq_x_item_y.split("/")
    return hq_x_item_y.replace(hq_x_item_array[-1:][0], "hq/" + hq_x_item_array[-1:][0])


def build_new_item(item_id, item):
    global items
    x_items = []
    if checkItemIsValid(item):
        x_item = {}
        x_item["Name"] = {
            "de": items[item_id]['Name_de'],
            "en": items[item_id]['Name_en'],
            "fr": items[item_id]['Name_fr'],
            "ja": items[item_id]['Name_ja'],
        }
        x_item["Level_Equip"] = int(item["LevelEquip"])
        x_item["Level_Item"] = int(item["LevelItem"]['row_id'])
        x_item["Rarity"] = int(item["Rarity"])
        #x_item["ItemSearchCategory"]          = item["ItemSearchCategory"]
        # Not needed as it is to detailed
        x_item["ItemUICategory"] = item["ItemUICategory"]
        x_item["ClassJobCategory"] = item["ClassJobCategory"]['Name_de']
        x_item["Icon"] = item["Icon"]['path'].replace(".tex", ".png")
        x_item["IsAdvancedMeldingPermitted"] = item["IsAdvancedMeldingPermitted"] == "True"
        x_item["MateriaSlotCount"] = int(item["MateriaSlotCount"])
        #x_item["IsDyeable"] = item["IsDyeable"] == "True"
        x_item["IsUnique"] = item["IsUnique"] == "True"
        x_item["IsUntradable"] = item["IsUntradable"] == "True"
        x_item["ItemSearchCategory"] = item["ItemSearchCategory"] != ""
        x_item["IsHQ"] = False
        x_item["LimitToHQ"] = False if item["CanBeHq"] == "True" else True
        x_item = handleStats(x_item, item)
        x_items.append(x_item)
        if item["CanBeHq"] == "True":
            hq_x_item = copy.deepcopy(x_items)[0]
            hq_x_item["Name"] = {
                "de": items[item_id]['Name_de'] + " ",
                "en": items[item_id]['Name_en'] + " ",
                "fr": items[item_id]['Name_fr'] + " ",
                "ja": items[item_id]['Name_ja'] + " ",
            }
            hq_x_item["Icon"] = getHQItemsPath(hq_x_item["Icon"])
            hq_x_item["IsHQ"] = True
            hq_x_item["LimitToHQ"] = True
            for x in range(0, 6):
                try:
                    stat = item["BaseParamSpecial"][x]['Name_de']
                    if hq_x_item["Stats"].get(stat, None):
                        v1 = int(hq_x_item["Stats"][stat])
                        v2 = int(item["BaseParamValueSpecial"][x])
                        hq_x_item["Stats"][stat] = v1 + v2
                except Exception as e:
                    print(e)
                    print(hq_x_item["Stats"])
                    print()
                    asd
                    pass
                    #print(f"Missing a parameter in {hq_x_item['Name']}: " + item[f"BaseParam_Special_[{x}]"])
            x_items.append(hq_x_item)
        # remove emtpy element if it is available
        for x in x_items:
            if x["Stats"].get("", None) == 0:
                del x["Stats"][""]
        return x_items
    return None


def writeLogdataFile(result):
    #result0 = f"{pretty_json(result)}"
    #result1 = re.sub(r'": \[\s+(?=\d)', '": [', result0)
    #result2 = re.sub(r'\s+\],', '],', result1)
    #result3 = re.sub(r'(?<=\d),\s+(?=\d)', ', ', result2)
    #print(result)
    writeJsonFile("../equipment.json", result, minified=True)


def assign_patches(result_dict):
    open_types = []
    patches = {}
    # get patches from github and reformat them
    with urllib.request.urlopen(r"https://raw.githubusercontent.com/xivapi/ffxiv-datamining-patches/master/patchlist.json") as f:
        d_patches = json.loads(f.read())
    for patch in d_patches:
        patches[patch['ID']] = patch['Version']
    #get item -> patch data from github
    with urllib.request.urlopen(r"https://raw.githubusercontent.com/xivapi/ffxiv-datamining-patches/master/patchdata/Item.json") as f:
        data = json.loads(f.read())

    for key, value in result_dict.items():
        try:
            for i, item in enumerate(value):
                result_dict[key][i]['Patch'] = patches[int(data[str(item['ID'])])]
        except:
            print_color_red(f"Error on item {item['ID']}")
    #print_pretty_json(result_dict)
    return result_dict


def run():
    print("[ffGG] New Gear")
    global items
    global items
    items = loadDataTheQuickestWay("Item.json")
    result_dict = {}
    for item_id, item_value in items.items():
        new_items = build_new_item(item_id, item_value)
        if new_items is None:
            continue
        for new_item in new_items:
            category = new_item["ItemUICategory"]['Name_de']
            if not result_dict.get(category, None):
                result_dict[category] = []
            del new_item["ItemUICategory"]
            new_item["ID"] = int(item_id.replace(".0", ""))
            result_dict[category].append(new_item)

    result_dict = assign_patches(result_dict)
    writeLogdataFile(result_dict)
    print("[ffGG] New Gear file created successfully!")


if __name__ == "__main__":
    run()
