import tkinter as tk
from tkinter import messagebox
from tkinter import filedialog
import os
import shutil

HTML_INSERT_TAG = "<!-- INSERT HERE -->"
uploaded_image_path = None  # Global to track uploaded image

def upload_image():
    global uploaded_image_path
    path = filedialog.askopenfilename(
        title="Select an Image",
        filetypes=[("Image Files", "*.png;*.jpg;*.jpeg;*.gif;*.mp4"), ("All Files", "*.*")]
    )
    if path:
        uploaded_image_path = path
        messagebox.showinfo("Image Uploaded", f"Selected image:\n{os.path.basename(path)}")


def submit_content():
    global uploaded_image_path

    date = date_text.get("1.0", tk.END).strip()
    title = title_text.get("1.0", tk.END).strip()
    content = content_text.get("1.0", tk.END).strip()
    img_lib = img_lib_text.get("1.0", tk.END).strip()

    if not date or not title or not content:
        messagebox.showerror("Error", "All fields must be filled out.")
        return

#    html_file_path = filedialog.askopenfilename(
#        title="Select HTML File",
#        filetypes=[("HTML files", "*.html"), ("All files", "*.*")]
#    )

#    if not html_file_path:
#        return
    html_file_path = './home.html'

    if not img_lib:
        new_entry = f"""
        <li><i>{date}</i></li>
        <li><b>{title}</b></li>
        <li>{content}</li>
        """
    else:
        new_entry = f"""
        <li><i>{date}</i></li>
        <li><b>{title}</b></li>
        <li>{content}</li>
        <li><a href="{img_lib}">Odkaz na foto galerii</a></li>
        """

    image_tag = ""
    if uploaded_image_path:
        try:
            html_dir = os.path.dirname(html_file_path)
            img_name = os.path.basename(uploaded_image_path)
            target_path = os.path.join(html_dir, img_name)
            target_path = "img/"+target_path[2:]
            print(target_path)

            # Copy image to HTML file directory
            shutil.copy(uploaded_image_path, target_path)
            if '.mp4' in target_path:
                image_tag = f'<li><video width="320" height="240" controls><source src="{target_path}" type="video/mp4" ></video></video></li>'
            else:
                image_tag = f'<li><img src="{target_path}" alt="Image" style="max-width:100%;"></li>'
        except Exception as e:
            messagebox.showwarning("Image Error", f"Could not copy image: {str(e)}")


    try:
        if not os.path.exists(html_file_path):
            with open(html_file_path, 'w') as f:
                f.write(f"<html><body>\n{HTML_INSERT_TAG}\n</body></html>")

        with open(html_file_path, 'r', encoding='utf-8') as f:
            html_content = f.read()

        if HTML_INSERT_TAG not in html_content:
            messagebox.showerror("Error", f"Insert tag '{HTML_INSERT_TAG}' not found in HTML file.")
            return

        full_entry = f"{new_entry}\n{image_tag}" if image_tag else new_entry
        new_html = html_content.replace(HTML_INSERT_TAG, f"{HTML_INSERT_TAG}\n{full_entry}")

        with open(html_file_path, 'w', encoding='utf-8') as f:
            f.write(new_html)

        messagebox.showinfo("Success", "Content inserted into HTML file.")
    except Exception as e:
        messagebox.showerror("Error", str(e))


# GUI Setup
root = tk.Tk()
root.title("HTML Content Inserter")
root.geometry("400x550")

tk.Label(root, text="Date:").pack(anchor='w', padx=10)
date_text = tk.Text(root, height=2, width=40)
date_text.pack(padx=10, pady=5)

tk.Label(root, text="Title:").pack(anchor='w', padx=10)
title_text = tk.Text(root, height=2, width=40)
title_text.pack(padx=10, pady=5)

tk.Label(root, text="Content:").pack(anchor='w', padx=10)
content_text = tk.Text(root, height=10, width=40)
content_text.pack(padx=10, pady=5)

upload_button = tk.Button(root, text="Upload Image/Video", command=upload_image)
upload_button.pack(pady=5)

tk.Label(root, text="Link to image library:").pack(anchor='w', padx=10)
img_lib_text = tk.Text(root, height=2, width=40)
img_lib_text.pack(padx=10, pady=5)

submit_button = tk.Button(root, text="Submit to HTML", command=submit_content)
submit_button.pack(pady=5)

root.mainloop()

