import mazegroup.commands as commands
import datetime
import os

class Command():
    def __init__(self) -> None:
        self.options_available = {
            "full": ["-f", "--full"]
        }

        self.version = "1"

        self.defaults = {
            "init": "\n".join(f"""
# __init__.py

\"\"\"
Package informations :
Name : <pkg_name>
Description : <pkg_description>
Author(s) : <pkg_author>
License : <pkg_license>
URL(s) : <pkg_url>
Creation date : <pkg_date>

Generated by MazeGroup.py Python Package Generator version {self.version}
MazeGroup Website : https://mazegroup.org/
MazeGroup.py GitHub : https://github.com/Geniusum/mazegroup.py
MazeGroup.py PyPi : https://pypi.org/project/mazegroup/
\"\"\"
""".splitlines()[1:]),
            "main": "\n".join(f"""
\"\"\"
Generated by MazeGroup.py Python Package Generator version {self.version}
MazeGroup Website : https://mazegroup.org/
MazeGroup.py GitHub : https://github.com/Geniusum/mazegroup.py
MazeGroup.py PyPi : https://pypi.org/project/mazegroup/
\"\"\"

import sys
import mazegroup as mg

class Main():
    def __init__(self, args:list=[]) -> None:
        self.args = args

    def script(self) -> any:
        pass # Your code here
        
if __name__ == "__main__":
    MainInstance = Main(sys.argv)
    MainInstance.script()
""".splitlines()[1:]),
            "package_json": "\n".join(f"""
{{
    "package": {{
        "name": "<pkg_name>",
        "description": "<pkg_description>",
        "author": "<pkg_author>",
        "license": "<pkg_license>",
        "url": "<pkg_url>",
        "date": "<pkg_date>"
    }},
    "from": "MazeGroup.py Python Package Generator version {self.version}"
}}
""".splitlines()[1:]),
            "package_xml": "\n".join(f"""
<data>
    <package>
        <name><pkg_name></name>
        <description><pkg_description></description>
        <author><pkg_author></author>
        <license><pkg_license></license>
        <url><pkg_url></url>
        <date><pkg_date></date>
    </package>
    <from>MazeGroup.py Python Package Generator version {self.version}</from>
</data>
""".splitlines()[1:]),
            "package_yml": "\n".join(f"""
package:
  name: "<pkg_name>"
  description: "<pkg_description>"
  author: "<pkg_author>"
  license: "<pkg_license>"
  url: "<pkg_url>"
  date: "<pkg_date>"
from: "MazeGroup.py Python Package Generator version {self.version}"
""".splitlines()[1:]),
            "package_csv": "\n".join(f"""
name,description,author,license,url,date,from
"<pkg_name>","<pkg_description>","<pkg_author>","<pkg_license>","<pkg_url>","<pkg_date>","MazeGroup.py Python Package Generator version {self.version}"
""".splitlines()[1:]),
            "package_toml": "\n".join(f"""
[package]
name = "<pkg_name>"
description = "<pkg_description>"
author = "<pkg_author>"
license = "<pkg_license>"
url = "<pkg_url>"
date = "<pkg_date>"

from = "MazeGroup.py Python Package Generator version {self.version}"
""".splitlines()[1:]),
            "package_ini": "\n".join(f"""
[package]
name = "<pkg_name>"
description = "<pkg_description>"
author = "<pkg_author>"
license = "<pkg_license>"
url = "<pkg_url>"
date = "<pkg_date>"

[from]
version = "MazeGroup.py Python Package Generator version {self.version}",
""".splitlines()[1:]),
            "package_py": "\n".join(f"""
package = {{
    "name": "<pkg_name>",
    "description": "<pkg_description>",
    "author": "<pkg_author>",
    "license": "<pkg_license>",
    "url": "<pkg_url>",
    "date": "<pkg_date>",
    "from": "MazeGroup.py Python Package Generator version {self.version}"
}}
""".splitlines()[1:])
        }

        self.tags = {
            "<pkg_name>": "",
            "<pkg_description>": "",
            "<pkg_author>": "",
            "<pkg_license>": "",
            "<pkg_url>": "",
            "<pkg_date>": ""
        }

        self.name = "pypkg"
        self.command_class = commands.Command(self.name, self.func, commands.Args([commands.Arg("name", required=True), commands.Arg("options", required=False)], overflow=True), True)
        self.command_class.register()
        
    def replaceTags(self, string:str) -> str:
        for key, value in self.tags.items(): string = string.replace(key, value)
        return string

    def optionOn(self, options:list, args:dict, option_type:str) -> bool:
        for option in options:
            arg = args[option]
            try:
                if str(arg.active_value).startswith("info:"):
                    infos = dict(eval(arg.active_value[5:]))
                    for tag in self.tags.keys():
                        try:
                            self.tags[tag] = infos[tag.replace("<pkg_", "").replace(">", "")]
                        except:
                            pass
            except: pass

        for option in options:
            arg = args[option]

            if arg.active_value in self.options_available[option_type]: return True
            return False

    def func(self, args:dict):
        options = list(args.keys())[1:]
        name = args["name"].active_value
        pkg_path = os.path.join(os.getcwd(), name)
        if not os.path.exists(pkg_path):
            try:
                self.tags["<pkg_name>"] = name
                self.tags["<pkg_date>"] = datetime.datetime.now().strftime("%d/%m/%Y")
                full = self.optionOn(options, args, "full")
                os.mkdir(pkg_path)
                init_file = open(os.path.join(pkg_path, "__init__.py"), "w")
                if full:
                    init_file.write(self.replaceTags(self.defaults["init"]))
                init_file.close()
                if full:
                    with open(os.path.join(pkg_path, "main.py"), "w") as f:
                        f.write(self.replaceTags(self.defaults["main"]))
                    with open(os.path.join(pkg_path, "package.json"), "w") as f:
                        f.write(self.replaceTags(self.defaults["package_json"]))
                    with open(os.path.join(pkg_path, "package.xml"), "w") as f:
                        f.write(self.replaceTags(self.defaults["package_xml"]))
                    with open(os.path.join(pkg_path, "package.yml"), "w") as f:
                        f.write(self.replaceTags(self.defaults["package_yml"]))
                    with open(os.path.join(pkg_path, "package.csv"), "w") as f:
                        f.write(self.replaceTags(self.defaults["package_csv"]))
                    with open(os.path.join(pkg_path, "package.toml"), "w") as f:
                        f.write(self.replaceTags(self.defaults["package_toml"]))
                    with open(os.path.join(pkg_path, "package.ini"), "w") as f:
                        f.write(self.replaceTags(self.defaults["package_ini"]))
                    with open(os.path.join(pkg_path, "package.py"), "w") as f:
                        f.write(self.replaceTags(self.defaults["package_py"]))
            except Exception as e:
                print(f"Error during the package generation : {e}")
        else:
            print("The directory already exists.")
            
Command()
