#!/usr/bin/env python3

#    This file is a part of the SteamWar software.
#
#    Copyright (C) 2024  SteamWar.de-Serverteam
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <https://www.gnu.org/licenses/>.

import datetime
import os
import shutil
import sys
import tarfile
from os import path

# Non stdlib
from nbt import nbt
from ruamel.yaml import YAML
yaml = YAML()

if __name__ == "__main__":
    configfile = f'/configs/GameModes/{sys.argv[1]}'
    version = int(sys.argv[2])
    worldname = sys.argv[3]

    with open(configfile, 'r') as file:
        gamemode = yaml.load(file)

    builderworld = path.expanduser(f'/worlds/builder{version}/{worldname}')
    arenaworld = f'/servers/{gamemode["Server"]["Folder"]}/arenas/{worldname}'

    if path.exists(arenaworld):
        backupworld = path.expanduser(f'/mnt/storage/backup/arenas/{datetime.datetime.now()}-{worldname}-{version}.tar.xz')
        with tarfile.open(backupworld, 'w:xz') as tar:
            tar.add(arenaworld, arcname=worldname)

        shutil.rmtree(arenaworld)
    else:
        gamemode['Server']['Maps'].append(worldname)

        with open(configfile, 'w') as file:
            yaml.dump(gamemode, file)


    level = nbt.NBTFile(f'{builderworld}/level.dat')
    level['Data']['Difficulty'] = nbt.TAG_Byte(2)
    gameRules = level['Data']['GameRules']
    gameRules['announceAdvancements'] = nbt.TAG_String('false')
    gameRules['disableRaids'] = nbt.TAG_String('true')
    gameRules['doDaylightCycle'] = nbt.TAG_String('false')
    gameRules['doEntityDrops'] = nbt.TAG_String('false')
    gameRules['doFireTick'] = nbt.TAG_String('true')
    gameRules['doImmediateRespawn'] = nbt.TAG_String('true')
    gameRules['doInsomnia'] = nbt.TAG_String('false')
    gameRules['doLimitedCrafting'] = nbt.TAG_String('false')
    gameRules['doMobLoot'] = nbt.TAG_String('false')
    gameRules['doMobSpawning'] = nbt.TAG_String('false')
    gameRules['doPatrolSpawning'] = nbt.TAG_String('false')
    gameRules['doTileDrops'] = nbt.TAG_String('true')
    gameRules['doTraderSpawning'] = nbt.TAG_String('false')
    gameRules['doWardenSpawning'] = nbt.TAG_String('false')
    gameRules['doWeatherCycle'] = nbt.TAG_String('false')
    gameRules['drowningDamage'] = nbt.TAG_String('true')
    gameRules['fallDamage'] = nbt.TAG_String('true')
    gameRules['fireDamage'] = nbt.TAG_String('true')
    gameRules['freezeDamage'] = nbt.TAG_String('true')
    gameRules['keepInventory'] = nbt.TAG_String('true')
    gameRules['lavaSourceConversion'] = nbt.TAG_String('false')
    gameRules['maxEntityCramming'] = nbt.TAG_String('24')
    gameRules['mobGriefing'] = nbt.TAG_String('false')
    gameRules['naturalRegeneration'] = nbt.TAG_String('false')
    gameRules['randomTickSpeed'] = nbt.TAG_String('3')
    gameRules['reducedDebugInfo'] = nbt.TAG_String('true')
    gameRules['snowAccumulationHeight'] = nbt.TAG_String('1')
    gameRules['spawnRadius'] = nbt.TAG_String('0')
    gameRules['spectatorsGenerateChunks'] = nbt.TAG_String('true')
    gameRules['waterSourceConversion'] = nbt.TAG_String('true')
    level.write_file()

    if path.exists(arenaworld):
        shutil.rmtree(arenaworld)

    os.makedirs(f'{arenaworld}/backup')
    shutil.copy2(f'{builderworld}/level.dat', f'{arenaworld}/backup/level.dat')
    shutil.copytree(f'{builderworld}/region', f'{arenaworld}/backup/region')

    shutil.copy2(f'{builderworld}/level.dat', f'{arenaworld}/level.dat')
    shutil.copytree(f'{builderworld}/region', f'{arenaworld}/region')
    shutil.copy2(f'{builderworld}/config.yml', f'{arenaworld}/config.yml')

    if path.exists(f'{builderworld}/paper-world.yml'):
        shutil.copy2(f'{builderworld}/paper-world.yml', f'{arenaworld}/backup/paper-world.yml')
        shutil.copy2(f'{builderworld}/paper-world.yml', f'{arenaworld}/paper-world.yml')
