#!/usr/bin/env python3

# edits the tag with "id={year}_entries" with an entry
# program for blog entries to my blog template hmtl, GUI, syntax is markdown
# to do: add new year

from bs4 import BeautifulSoup
from pathlib import Path
import inquirer
from time import strftime, gmtime, time
import calendar
import datetime as dt
import re
import tkinter as tk
from tkinter import ttk
import markdown
import sys
import json
# from build_rss import build_rss


def create_time_id_from_string(dmy: str):
    d, m, y = dmy.strip().split('.')
    usc_time_tuple = (int(y), int(m), int(d), 0, 0, 1)
    time_id = calendar.timegm(usc_time_tuple)
    return time_id
    

def entry_GUI(date_str: str, file_w, time_id = -1):
    text_entry = ""

    root = tk.Tk()
    frame = ttk.Frame (root, width=900)
    frame.grid()
    text_win = tk.Text(frame)
    text_win.grid(column=0, columnspan=1, row=0)
    
    # process the date string
    day, month, year = date_str.strip().split('.')
    print(f"day, month, year:{day, month, year}")
    
    if time_id == -1:
        time_id = create_time_id_from_string(date_str)
        print(f"Time ID generated: {time_id}")
    else:
        print(f"Current ID: {time_id}")
        
    
    def process_text(time_id, file_w):
        
        ## proccess the markdown entry ##
        
        entry = text_win.get('1.0', 'end')
        # create a proper html code from markdown
        entry = f"<html><article class='entry_div' data-time_id='{str(time_id)}'>{markdown.markdown(entry)}</article></html>"
        #parse the entry - create an bs object from the entry
        entry_soup = BeautifulSoup(entry, 'html.parser')
        ## add the year to entry div
        new_entry = entry_soup.find('article', {'class': 'entry_div'}) ## entry_div is the class of newly added tag to be recognised later as an entry
        new_date_tag = entry_soup.new_tag('h2', string = date_str)
        new_entry.insert(0, new_date_tag)
        #--> výsledkem je div se vším co má být, teď jen najít a přiddat tam, dke má být
        
        
        for f in file_w:
            print(f"Working on {str(f)}")
            with open(f) as fp:
                soup = BeautifulSoup(fp, 'html.parser') # open the 
                id_entry_block = year + "_entries"
                try:
                    # najdi tag roku, do kterého se bude psát
                    entry_block = soup.find('div', {'id': id_entry_block}) ##!! if year does not exist you have to create it manually for now
                
                except AttributeError as e:
                    print("Year not found. Create tag for this year's entries. Or maybe there has been some other problem:")
                    print(e)
                      
            ## get the index where to write (for blogging with older date than is the last one)
            # format the date of entry to enable sorting of entries
            date_of_new_entry = dt.date(int(year), int(month), int(day))
            
            all_years_entries = entry_block.find_all('article', {'class': 'entry_div'})
                
                
            # get index of tag and its time id, add to list
            ids = []
            
            for past_entry in all_years_entries:
                
                tag_index = int(past_entry.parent.contents.index(past_entry))
                
                try:
                    print(f"Trying to get id - output: {past_entry.get('data-time_id')}")
                    get_time_id = float(past_entry.get('data-time_id'))
                    print(f"get_pos outcome: {tag_index}")
                except Exception as e:
                    try:
                        entry_date_str = past_entry.find('h4').string
                        print(f"Trying to create time id from: {entry_date_str}")
                        get_time_id = create_time_id_from_string(entry_date_str)
                    except Exception as e:
                        print(f"While trying to get ID of tag, error occured, propably no id exists for entry: \n {past_entry} \n Error message:{e}")
                
                ids.append([get_time_id, tag_index])
            
            print(ids)
            
            tag_index = 0 # starting position where to put the new entry tag
            
            #compare the time ids and decide where to insert newly created entry
            
            for a in ids:
                this_time_id = a[0]
                idxy = a[1]
                print(f"Time id for this past entry: {this_time_id}")
                if time_id < this_time_id:
                    tag_index = idxy + 1 ## put it after this tag
                    print (f"time id is less than this id, index ({tag_index}) becomes idxy ({idxy}) + 1")
                    
                elif time_id == this_time_id:
                    tag_index = idxy ## put it instead of this tag
                    print (f"time id equals this id, index ({tag_index}) becomes idxy ({idxy}) + 1")
                else:
                    # print(index)
                    print ("Passed")
                    pass
                
                
            ## add the converted markdown entry
            entry_block.insert(tag_index, new_entry)
            
            with open(f, 'w', encoding="utf-8") as nhtml:
                nhtml.write(str(soup.prettify()))
                print(f"New blog entry added at index {tag_index}. Now go and look around you! There is so much to see and hear.")
            
        root.destroy()

    button = ttk.Button(frame, text="add", command=lambda: process_text(time_id, file_w))
    button.grid(column=1, row=1)
    root.mainloop()
    return text_entry

## body of script

base_dir = Path(__file__).resolve().parent ## operating in the directory of the script

try:
    resource_fold_path =  Path(base_dir/"blog_resources").mkdir(parents=True, exist_ok=False)
except FileExistsError:
    resource_fold_path = Path(base_dir/"blog_resources")
    
files_paths = Path(base_dir/"blog_resources"/"files_paths.json")
if not files_paths.is_file():
    private_path = Path(input("Enter the path to the private folder:"))
    public_path = Path(input("Enter the path to public folder:"))
    with open(files_paths, "w") as f:
        paths_json = json.dumps({"private": str(private_path), "public": str(public_path)})
        f.write(paths_json)
else:
    with open(files_paths, "r") as f:
        paths_json = json.load(f)
        private_path = Path(paths_json["private"])
        public_path = Path(paths_json["public"])
print(public_path, private_path)
    

# question what mode - private/public
q_mode = [inquirer.List('mode', message="Mode:", choices = ["private", "public"])]
a_mode = inquirer.prompt(q_mode)

if a_mode["mode"] == "private":
    file_w_parent = [private_path]
if a_mode["mode"] == "public":
    file_w_parent = [private_path, public_path]

path_opts = list(private_path.glob('*.html'))
opts = []
for p in path_opts:
    opts.append(p.stem)
  
questions = [inquirer.List('where', message="Kam si přeješ psát?", choices=opts)]
print(questions)

answer = inquirer.prompt(questions)

if answer:
    file_w = []
    for p in file_w_parent:
        where = answer['where'] + '.html'
        file_w.append(Path(p/where))
        print (f'Writing to {str(Path(p/where))}.')
else:
    print("No file chosen. Bye!")

## now ask if the entry should carry todays date or some other date
sg_year = strftime("%Y", gmtime())
sg_month = re.sub(r"\A0", "", strftime("%m", gmtime()))
sg_day = re.sub(r"\A0", "", strftime("%d", gmtime()))
sgstd_date = '.'.join([sg_day, sg_month, sg_year])


date_opts = [sgstd_date, "other"]
question_date = [inquirer.List('date', message='Date:', choices=date_opts)]
answered_date = inquirer.prompt(question_date)



if answered_date['date'] == "other":
    date_str = input("date(d.m.y): ")
    time_id = -1 # nonsence, but will be genarated from date_str in entry_GUI function
else: 
    date_str = sgstd_date
    time_id = time()

# procceed to creating the entry

if date_str:
    entry_GUI(date_str, file_w, time_id)
else: print("No date given. Or maybe something else happened. Bye!")


# # create rss

# if a_mode["mode"] == "public":
    # build_rss(file_w, public_path/"rss_new.xml", "jeravi's observations'")
    
sys.exit()
