import users
import posts
import rebuild

import click

def editpost(userID, datetime):
    post_counter = 0
    user_posts = []
    print("Which post do you want to edit?")
    for current_post_index in range(len(posts.posts)):
        if posts.posts[current_post_index]["userID"] == userID:
            print(f"{post_counter}: {posts.posts[current_post_index]['title']}")
            post_counter += 1
            user_posts.append(posts.posts[current_post_index])

    try:
        post_to_edit_index = int(input())
    except:
        print("Failed to read input, did you input a number?")

    print(f'''You selected:
Title: {posts.posts[post_to_edit_index]['title']}
Content: {posts.posts[post_to_edit_index]['content']}
''')
    print('''0. Edit post's (T)itle
1. Edit post's (C)ontent
2. (D)elete post''')
    answer = input()

    if answer == "0" or answer == "T": # Editing the title
        title = click.edit(posts.posts[post_to_edit_index]['title'])
        title = title.replace("'", "\'")
        posts.posts[post_to_edit_index]['title'] = title
        posts.posts[post_to_edit_index]['editdate'] = datetime.now().strftime("%d%m%YZ%H%M%ST")

    elif answer == "1" or answer == "C": # Editing the content
        content = click.edit(posts.posts[post_to_edit_index]['content'])
        content = content.replace("'", "\'")
        posts.posts[post_to_edit_index]['content'] = content
        posts.posts[post_to_edit_index]['editdate'] = datetime.now().strftime("%d%m%YZ%H%M%ST")

    elif answer == "2" or answer == "D": # Editing the existence
        print("Are you sure you want to delete it? There is no undoing!\n(Y/n)")
        if input().upper() == "Y":
            posts.posts.pop(post_to_edit_index)
        else:
            exit()

    with open("posts.py", "w") as posts_file:
        posts_file.write(f"posts = {posts.posts}")

    rebuild.rebuild()