#!/usr/bin/python3

import argparse
import re
# this assumes a mostly semver-complient version number

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Increment GamecraftModdingAPI version")
    parser.add_argument('version', metavar="VN", type=str, help="The version number to increment, or the index of the number (zero-indexed).")
    args = parser.parse_args()
    
    version_index = -1
    try:
        version_index = int(args.version)
    except Exception:
        if args.version.lower() == "major":
            version_index = 0
        elif args.version.lower() == "minor":
            version_index = 1
        elif args.version.lower() == "patch":
            version_index = 2
    
    if version_index < 0:
        print("Could not parse version argument.")
        exit(version_index)
    
    print(version_index)
    old_version = ""
    new_version = ""
    
    with open("../GamecraftModdingAPI/GamecraftModdingAPI.csproj", "r") as xmlFile:
        print("Parsing GamecraftModdingAPI.csproj")
        fileStr = xmlFile.read()
        versionMatch = re.search(r"<Version>(.+)</Version>", fileStr)
        if versionMatch is None:
            print("Unable to find version number in GamecraftModdingAPI.csproj")
            exit(1)
        old_version = versionMatch.group(1)
        versionList = old_version.split(".")
        if len(versionList) <= version_index:
            print("Invalid version string")
            exit(1)
        versionList[version_index] = str(int(versionList[version_index]) + 1)
        for i in range(version_index + 1, len(versionList)):
            try:
                int(versionList[i])
                versionList[i] = "0"
            except Exception:
                tmp = versionList[i].split("-")
                tmp[0] = "0"
                versionList[i] = "-".join(tmp)
        new_version = ".".join(versionList)
        print(new_version)
        newFileContents = fileStr.replace("<Version>"+old_version+"</Version>", "<Version>"+new_version+"</Version>")
        
    with open("../GamecraftModdingAPI/GamecraftModdingAPI.csproj", "w") as xmlFile:
        print("Writing new version to project file")
        xmlFile.write(newFileContents)
    
    with open("../doxygen.conf", "r") as doxFile:
        print("Parsing doxygen.conf")
        doxStr = doxFile.read()
        newFileContents = doxStr.replace("= \"v" + old_version + "\"", "= \"v" + new_version + "\"")
    
    with open("../doxygen.conf", "w") as doxFile:
        print("Writing new version to doxygen config")
        doxFile.write(newFileContents)