import sys # Command line arguments
from importlib.machinery import SourceFileLoader
from datetime import datetime
import newpost
import editpost
import rebuild
import initialise

config_file_path = "config.py"
if len(sys.argv) > 1:
    for argument in sys.argv:
        if argument[:9] == "--config=":
            config_file_path = argument[9:]

try:
    import posts
except:
    print("No posts database")
    initialise.initialise()
try:
    import users
except:
    print("No users database")
    initialise.initialise()
try:
    config = SourceFileLoader("config", config_file_path).load_module()
    if config.autogenerated == True:
        print("Error: autogenerated = True")
        exit()
except:
    print("Please move example.config.py to config.py and edit the options to your case and then set autogenerated=False")
    exit()

if len(sys.argv) > 1:
    for argument in sys.argv:
        if argument == "--help":
            print('''
If no argument is passed, glogger will ask for a username;
if that user exists, it will as if you want to create a new post, or edit a post (TODO)
                  --help    Output this help text
                  --rebuild Rewrite every static page in the site
                  ''')
            exit()
        if argument == "--rebuild":
            rebuild.rebuild()
            exit()

username = input("Username: ").lower()

# Check if this user exists
user_present = False
for current_user in range(len(users.users)):
	if users.users[current_user] == username:
		user_present = True
		userID = current_user
if user_present == True:
    print('''What do you want to do?
    0. Create (N)ew post
    1. (E)dit a post''')

    answer = input()
    if answer == 'N' or answer == '0':
        newpost.newpost(userID, username, datetime, config, posts, users)
    if answer == 'E' or answer == '1':
        editpost.editpost(userID, datetime, config, posts, users)
else:
	print('Sorry, that account does not exist, If it should, please ask the webadmin to add this account')