#!/usr/bin/python3
# -*- coding: utf8 -*-

import xml.dom.minidom


def main():
    swords = []
    bows = []
    shields = []

    dom = xml.dom.minidom.parse('../../client-data/items.xml')

    # get root element
    root = dom.documentElement

    # get item elements
    items = root.getElementsByTagName("item")
    list_items = []

    for item in items:
        item_id = item.getAttribute("id")
        item_level = item.getAttribute("level")

        if not item_level:
            continue

        try:
            item_id = int(item_id)
        except Exception as e:
            print(f"{e} - [CRITICAL] Invalid item ID format: {item_id}")
            return

        try:
            item_level = int(item_level)
        except Exception as e:
            print(f"{e} - [CRITICAL] Invalid item level format: {item_level}")
            return

        list_items.append(item_id)

    for item_id in sorted(list_items):
        if item_id >= 2700 and item_id <= 2899:
            shields.append(item_id)
        elif item_id >= 3500 and item_id <= 3999:
            swords.append(item_id)
        elif item_id >= 6000 and item_id <= 6499:
            bows.append(item_id)

    # shields = sorted(shields, reverse=True)
    # bows = sorted(bows, reverse=True)
    # swords = sorted(swords, reverse=True)

    with open('weapons.tmp', 'w', encoding='UTF-8') as f:
        print('<?xml version="1.0" encoding="utf-8"?>\n\
        <!-- Author: 4144, Jesusalva\n\
        Copyright (C) 2015 Evol Online\n\
        Copyright (C) 2018 TMW2: Moubootaur Legends\n -->\n\
        \n\
        <weapons>', file=f)

        print('    <swords>', file=f)
        for i in swords:
            print(f'        <item id="{i}"/>', file=f)
        print('    </swords>', file=f)

        print('    <bows>', file=f)
        for i in bows:
            print(f'        <item id="{i}"/>', file=f)
        print('    </bows>', file=f)

        print('    <shields>', file=f)
        for i in shields:
            print(f'        <item id="{i}"/>', file=f)
        print('    </shields>', file=f)

        print('</weapons>', file=f)


if __name__ == '__main__':
    main()