from categories import get_categories
import gi
import os
import sqlite3
from datetime import datetime
from categories import (
    get_categories,
    add_category,
    rename_category_db,
    delete_category_db
)
gi.require_version("Gtk", "4.0")
from gi.repository import Gtk, GLib, Gio


class IdeaBox(Gtk.Application):
    
    def delete_category(self, widget, category):

        dialog = Gtk.Window(
            title="Delete Category"
        )

        dialog.set_default_size(
            400,
            180
        )

        dialog.set_transient_for(
            widget.get_root()
        )

        dialog.set_modal(True)

        box = Gtk.Box(
            orientation=Gtk.Orientation.VERTICAL,
            spacing=10
        )

        box.set_margin_top(15)
        box.set_margin_bottom(15)
        box.set_margin_start(15)
        box.set_margin_end(15)

        message = Gtk.Label(
            label=f"Delete category '{category}'?"
        )

        message.set_wrap(True)

        box.append(message)

        button_box = Gtk.Box(
            orientation=Gtk.Orientation.HORIZONTAL,
            spacing=10
        )

        button_box.set_halign(
            Gtk.Align.END
        )

        cancel_button = Gtk.Button(
            label="Cancel"
        )

        cancel_button.connect(
            "clicked",
            lambda button: dialog.close()
        )

        button_box.append(
            cancel_button
        )

        delete_button = Gtk.Button(
            label="Delete"
        )

        button_box.append(
            delete_button
        )

        box.append(
            button_box
        )

        def do_delete(button):

            deleted, count = delete_category_db(
                self.db,
                category
            )

            if not deleted:

                message.set_text(
                    f"This category is used by "
                    f"{count} idea(s) and cannot be deleted."
                )

                return

            manage_window = widget.get_root()

            dialog.close()

            manage_window.close()

            self.load_ideas()

            self.manage_categories()

        delete_button.connect(
            "clicked",
            do_delete
        )

        dialog.set_child(box)

        dialog.present()    
    def add_category(self, widget):

        dialog = Gtk.Window(
            title="Add Category"
        )

        dialog.set_default_size(350, 150)

        dialog.set_transient_for(
            widget.get_root()
        )

        dialog.set_modal(True)

        box = Gtk.Box(
            orientation=Gtk.Orientation.VERTICAL,
            spacing=10
        )

        box.set_margin_top(15)
        box.set_margin_bottom(15)
        box.set_margin_start(15)
        box.set_margin_end(15)

        entry = Gtk.Entry()

        entry.set_placeholder_text(
            "Category name"
        )

        box.append(entry)

        button_box = Gtk.Box(
            orientation=Gtk.Orientation.HORIZONTAL,
            spacing=10
        )

        button_box.set_halign(
            Gtk.Align.END
        )

        cancel_button = Gtk.Button(
            label="Cancel"
        )

        cancel_button.connect(
            "clicked",
            lambda button: dialog.close()
        )

        button_box.append(
            cancel_button
        )

        add_button = Gtk.Button(
            label="Add"
        )

        button_box.append(
            add_button
        )

        box.append(
            button_box
        )

        def do_add(button):

            name = entry.get_text().strip()

            if not name:
                return

            add_category(
                self.db,
                name
            )

            manage_window = widget.get_root()

            dialog.close()

            manage_window.close()

            self.manage_categories()

        add_button.connect(
            "clicked",
            do_add
        )

        dialog.set_child(
            box
        )

        dialog.present()    

        
    def __init__(self):
        super().__init__(
            application_id="uk.co.strus.IdeaBox"
        )
    
        self.setup_database()
    
        new_idea_action = Gio.SimpleAction.new(
            "new_idea",
            None
        )
    
        new_idea_action.connect(
            "activate",
            self.new_idea_shortcut
        )
        
        self.add_action(new_idea_action)
    
        self.set_accels_for_action(
            "app.new_idea",
            ["<Control>n"]
        )

    def setup_database(self):
    
        data_dir = os.path.expanduser(
            "~/.local/share/ideabox"
        )
    
        os.makedirs(data_dir, exist_ok=True)
    
        db_path = os.path.join(
            data_dir,
            "ideas.db"
        )
    
        self.db = sqlite3.connect(db_path)
    
        self.db.execute("""
            CREATE TABLE IF NOT EXISTS ideas (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                title TEXT NOT NULL,
                category TEXT NOT NULL,
                status TEXT NOT NULL,
                notes TEXT,
                created_at TEXT NOT NULL,
                updated_at TEXT NOT NULL
            )
        """)
    
        self.db.execute("""
            CREATE TABLE IF NOT EXISTS categories (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT NOT NULL UNIQUE
            )
        """)
    
        categories = [
            "Software",
            "Hardware",
            "Website",
            "Amateur Radio",
            "Linux",
            "Other"
        ]
    
        for category in categories:
    
            self.db.execute("""
                INSERT OR IGNORE INTO categories (name)
                VALUES (?)
            """, (category,))
    
        self.db.commit()
        
    def new_idea_shortcut(self, action, parameter):

        self.new_idea(None)
    
    def do_activate(self):
    
        window = Gtk.ApplicationWindow(application=self)
        window.set_title("IdeaBox")
        window.set_default_size(800, 500)
    
        main_box = Gtk.Box(
            orientation=Gtk.Orientation.VERTICAL,
            spacing=10
        )
    
        main_box.set_margin_top(15)
        main_box.set_margin_bottom(15)
        main_box.set_margin_start(15)
        main_box.set_margin_end(15)
    
        # Heading
        title = Gtk.Label()
        title.set_markup("<big><b>My Ideas</b></big>")
        title.set_xalign(0)
    
        main_box.append(title)
    
        # Search box and New Idea button
        search_entry = Gtk.Entry()
        search_entry.set_placeholder_text("Search ideas...")
        search_entry.set_hexpand(True)
        
        self.search_entry = search_entry
        
        search_entry.connect(
            "changed",
            self.search_ideas
        )
        
        include_archived = Gtk.CheckButton(
            label="Include archived"
        )
        
        include_archived.connect(
            "toggled",
            self.search_ideas
        )
        
        self.include_archived = include_archived
        
        new_button = Gtk.Button(label="+ New Idea")
        new_button.set_halign(Gtk.Align.START)
        new_button.connect("clicked", self.new_idea)
        
        categories_button = Gtk.Button(
            label="Manage Categories"
        )
        
        categories_button.connect(
            "clicked",
            self.manage_categories
        )
        
        header = Gtk.Box(
            orientation=Gtk.Orientation.HORIZONTAL,
            spacing=10
        )
        
        header.append(search_entry)
        header.append(include_archived)
        header.append(new_button)
        header.append(categories_button)
        main_box.append(header)
   
        # Category and Status filters

        category_options = [
            "All categories"
        ] + get_categories(self.db)

        category_filter = Gtk.DropDown.new_from_strings(
            category_options
        )

        category_filter.set_selected(0)

        category_filter.connect(
            "notify::selected",
            self.search_ideas
        )

        self.category_filter = category_filter
        self.category_options = category_options

        filter_box = Gtk.Box(
            orientation=Gtk.Orientation.HORIZONTAL,
            spacing=10
        )

        category_label = Gtk.Label(
            label="Category:"
        )

        category_label.set_xalign(0)

        filter_box.append(category_label)
        filter_box.append(category_filter)


        # Status filter

        status_options = [
            "All statuses",
            "Idea",
            "Considering",
            "Working On",
            "Finished",
            "Abandoned"
        ]

        status_filter = Gtk.DropDown.new_from_strings(
            status_options
        )

        status_filter.set_selected(0)

        status_filter.connect(
            "notify::selected",
            self.search_ideas
        )

        self.status_filter = status_filter
        self.status_options = status_options

        status_label = Gtk.Label(
            label="Status:"
        )

        status_label.set_xalign(0)

        filter_box.append(status_label)
        filter_box.append(status_filter)


        main_box.append(filter_box)
        
        # Ideas list

        self.ideas_box = Gtk.Box(
            orientation=Gtk.Orientation.VERTICAL,
            spacing=5
        )

        self.ideas_box.set_vexpand(True)

        scrolled = Gtk.ScrolledWindow()
        scrolled.set_vexpand(True)
        scrolled.set_child(self.ideas_box)

        main_box.append(scrolled)
            
        # Load saved ideas
        self.load_ideas()
    
        window.set_child(main_box)
        window.present()
        
    def search_ideas(self, widget=None, param=None):

        search_text = self.search_entry.get_text()

        include_archived = (
            self.include_archived.get_active()
        )

        category_selected = (
            self.category_filter.get_selected()
        )

        if category_selected == 0:

            category_filter = ""

        else:

            category_filter = (
                self.category_options[category_selected]
            )

        status_selected = (
            self.status_filter.get_selected()
        )

        if status_selected == 0:

            status_filter = ""

        else:

            status_filter = (
                self.status_options[status_selected]
            )

        self.load_ideas(
            search_text,
            include_archived,
            category_filter,
            status_filter
        )
         
    def load_ideas(self, search_text="", include_archived=False, category_filter="", status_filter="" ):

        # Remove anything currently displayed
        child = self.ideas_box.get_first_child()

        while child:
            next_child = child.get_next_sibling()
            self.ideas_box.remove(child)
            child = next_child

        search_text = search_text.strip()

        # Get ideas from database

        conditions = []
        parameters = []

        # Search text
        if search_text.strip():

            search_pattern = "%" + search_text.strip() + "%"

            conditions.append(
                "(title LIKE ? OR notes LIKE ?)"
            )

            parameters.extend([
                search_pattern,
                search_pattern
            ])

        # Category filter
        if category_filter:

            conditions.append(
                "category = ?"
            )

            parameters.append(
                category_filter
            )

        # Status filter
        if status_filter:

            conditions.append(
                "status = ?"
            )

            parameters.append(
                status_filter
            )

        # Hide archived ideas unless requested
        if not include_archived:

            conditions.append(
                "status NOT IN ('Finished', 'Abandoned')"
            )

        sql = """
            SELECT
                id,
                title,
                category,
                status,
                notes,
                created_at
            FROM ideas
        """

        if conditions:

            sql += " WHERE "
            sql += " AND ".join(conditions)

        sql += """
            ORDER BY
                CASE
                    WHEN status IN ('Finished', 'Abandoned') THEN 1
                    ELSE 0
                END,
                id DESC
        """

        cursor = self.db.execute(
            sql,
            parameters
        )
        

        ideas = cursor.fetchall()

        if not ideas:

            label = Gtk.Label(
                label="No ideas found."
            )

            label.set_vexpand(True)
            label.set_valign(Gtk.Align.CENTER)

            self.ideas_box.append(label)

            return

        for idea in ideas:

            idea_id = idea[0]
            title = idea[1]
            category = idea[2]
            status = idea[3]
            notes = idea[4] or ""

            # Make a short notes preview
            notes_preview = notes.replace(
                "\n", " "
            ).replace(
                "\r", " "
            ).strip()

            if len(notes_preview) > 30:
                notes_preview = notes_preview[:30] + "..."

            # Create a grid for the idea
            grid = Gtk.Grid()

            grid.set_column_spacing(15)
            grid.set_row_spacing(2)

            # Title
            escaped_title = GLib.markup_escape_text(title)

            title_label = Gtk.Label()

            title_label.set_markup(
                f"<b>{escaped_title}</b>"
            )

            title_label.set_xalign(0)
            title_label.set_width_chars(35)
            title_label.set_max_width_chars(35)
            title_label.set_ellipsize(3)
            title_label.set_size_request(260, -1)

            grid.attach(
                title_label,
                0, 0, 1, 1
            )

            # Category
            category_label = Gtk.Label(
                label=category
            )

            category_label.set_xalign(0)
            category_label.set_size_request(130, -1)

            grid.attach(
                category_label,
                1, 0, 1, 1
            )

            # Status
            status_label = Gtk.Label()

            escaped_status = GLib.markup_escape_text(status)

            if status == "Idea":
                status_colour = "black"

            elif status == "Considering":
                status_colour = "darkorange"

            elif status == "Working On":
                status_colour = "blue"

            elif status == "Finished":
                status_colour = "darkgreen"

            elif status == "Abandoned":
                status_colour = "red"

            else:
                status_colour = "black"

            status_label.set_markup(
                f"<b><span foreground='{status_colour}'>{escaped_status}</span></b>"
            )

            status_label.set_xalign(0)
            status_label.set_size_request(120, -1)

            grid.attach(
                status_label,
                2, 0, 1, 1
            )

            # Notes preview
            notes_label = Gtk.Label(
                label=notes_preview
            )

            notes_label.set_xalign(0)
            notes_label.set_hexpand(True)
            notes_label.set_ellipsize(3)

            grid.attach(
                notes_label,
                3, 0, 1, 1
            )

            # Frame around the idea
            frame = Gtk.Frame()

            frame.set_margin_top(2)
            frame.set_margin_bottom(2)
            frame.set_child(grid)

            # Make the whole entry clickable
            click = Gtk.GestureClick()

            click.connect(
                "released",
                lambda gesture,
                       n_press,
                       x,
                       y,
                       idea_id=idea_id:
                    self.view_idea(idea_id)
            )

            frame.add_controller(click)

            self.ideas_box.append(frame)   
        
    def view_idea(self, idea_id):
    
        cursor = self.db.execute("""
            SELECT
                title,
                category,
                status,
                notes,
                created_at,
                updated_at
            FROM ideas
            WHERE id = ?
        """, (idea_id,))
    
        idea = cursor.fetchone()
    
        if not idea:
            return
    
        title = idea[0]
        category = idea[1]
        status = idea[2]
        notes = idea[3] or ""
        created_at = idea[4]
        updated_at = idea[5]
    
        window = Gtk.Window()
    
        window.set_title("Edit Idea")
        window.set_default_size(600, 500)
    
        box = Gtk.Box(
            orientation=Gtk.Orientation.VERTICAL,
            spacing=10
        )
    
        box.set_margin_top(15)
        box.set_margin_bottom(15)
        box.set_margin_start(15)
        box.set_margin_end(15)
    
        # Title
        label = Gtk.Label(
            label="Title"
        )
    
        label.set_xalign(0)
    
        box.append(label)
    
        title_entry = Gtk.Entry()
    
        title_entry.set_text(title)
    
        box.append(title_entry)
    
        # Category
        label = Gtk.Label(
            label="Category"
        )
    
        label.set_xalign(0)
    
        box.append(label)
    
        category_options = get_categories(self.db)
        
        category_dropdown = Gtk.DropDown.new_from_strings(
            category_options
        )
    
        category_index = category_options.index(category)
    
        category_dropdown.set_selected(
            category_index
        )
    
        box.append(category_dropdown)
    
        # Status
        label = Gtk.Label(
            label="Status"
        )
    
        label.set_xalign(0)
    
        box.append(label)
    
        status_options = [
            "Idea",
            "Considering",
            "Working On",
            "Finished",
            "Abandoned"
        ]
    
        status_dropdown = Gtk.DropDown.new_from_strings(
            status_options
        )
    
        status_index = status_options.index(status)
    
        status_dropdown.set_selected(
            status_index
        )
    
        box.append(status_dropdown)
    
        # Notes
        label = Gtk.Label(
            label="Notes"
        )
    
        label.set_xalign(0)
    
        box.append(label)
    
        notes_view = Gtk.TextView()
    
        notes_view.set_wrap_mode(
            Gtk.WrapMode.WORD
        )
    
        notes_view.set_vexpand(True)
    
        notes_buffer = notes_view.get_buffer()
    
        notes_buffer.set_text(notes)
    
        box.append(notes_view)
    
        # Dates
        dates = Gtk.Label(
            label=(
                f"Created: {created_at}\n"
                f"Updated: {updated_at}"
            )
        )
    
        dates.set_xalign(0)
    
        box.append(dates)
    
        # Buttons
        button_box = Gtk.Box(
            orientation=Gtk.Orientation.HORIZONTAL,
            spacing=10
        )
    
        button_box.set_halign(
            Gtk.Align.END
        )
    
        cancel_button = Gtk.Button(
            label="Cancel"
        )
    
        cancel_button.connect(
            "clicked",
            lambda button: window.close()
        )
    
        save_button = Gtk.Button(
            label="Save Changes"
        )
    
        save_button.connect(
            "clicked",
            lambda button: self.update_idea(
                window,
                idea_id,
                title_entry,
                category_dropdown,
                status_dropdown,
                notes_view
            )
        )
    
        button_box.append(cancel_button)
        button_box.append(save_button)
    
        box.append(button_box)
    
        window.set_child(box)
    
        window.set_transient_for(
            self.get_active_window()
        )
    
        window.present()

    def update_idea(
        self,
        window,
        idea_id,
        title_entry,
        category_dropdown,
        status_dropdown,
        notes_view
    ):
    
        # Get the new title
        title = title_entry.get_text().strip()
    
        if not title:
    
            error = Gtk.AlertDialog()
    
            error.set_message(
                "Please enter a title."
            )
    
            error.show(window)
    
            return
    
        # Get the selected category
        category_item = (
            category_dropdown.get_selected_item()
        )
    
        category = category_item.get_string()
    
        # Get the selected status
        status_item = (
            status_dropdown.get_selected_item()
        )
    
        status = status_item.get_string()
    
        # Get the notes
        notes_buffer = notes_view.get_buffer()
    
        start_iter = notes_buffer.get_start_iter()
        end_iter = notes_buffer.get_end_iter()
    
        notes = notes_buffer.get_text(
            start_iter,
            end_iter,
            False
        )
    
        # Update the date/time
        updated_at = datetime.now().strftime(
            "%Y-%m-%d %H:%M:%S"
        )
    
        # Update the database
        self.db.execute("""
            UPDATE ideas
            SET
                title = ?,
                category = ?,
                status = ?,
                notes = ?,
                updated_at = ?
            WHERE id = ?
        """, (
            title,
            category,
            status,
            notes,
            updated_at,
            idea_id
        ))
    
        self.db.commit()
    
        print("Idea updated.")
    
        # Close the edit window
        window.close()
    
        # Refresh the main list
        self.load_ideas()
    def manage_categories(self, widget=None):

        window = Gtk.Window(
            title="Manage Categories"
        )

        window.set_default_size(400, 300)

        box = Gtk.Box(
            orientation=Gtk.Orientation.VERTICAL,
            spacing=10
        )

        box.set_margin_top(15)
        box.set_margin_bottom(15)
        box.set_margin_start(15)
        box.set_margin_end(15)

        title = Gtk.Label()
        title.set_markup("<big><b>Categories</b></big>")
        title.set_xalign(0)

        box.append(title)

        categories = get_categories(self.db)

        for category in categories:
        
            row = Gtk.Box(
                orientation=Gtk.Orientation.HORIZONTAL,
                spacing=10
            )
        
            label = Gtk.Label(
                label=category
            )
        
            label.set_xalign(0)
            label.set_hexpand(True)
        
            row.append(label)
        
            rename_button = Gtk.Button(
                label="Rename"
            )
        
            rename_button.connect(
                "clicked",
                self.rename_category,
                category
            )
        
            row.append(rename_button)
            
            delete_button = Gtk.Button(
                label="Delete"
            )
        
            delete_button.connect(
                "clicked",
                self.delete_category,
                category
            )
        
            row.append(delete_button)
        
            box.append(row)

        close_button = Gtk.Button(
            label="Close"
        )

        add_button = Gtk.Button(
            label="Add Category"
        )
        
        add_button.set_halign(Gtk.Align.START)
        
        add_button.connect(
            "clicked",
            self.add_category
        )
        
        box.append(add_button)

        close_button.set_halign(Gtk.Align.END)

        close_button.connect(
            "clicked",
            lambda button: window.close()
        )

        box.append(close_button)

        window.set_child(box)

        window.present()
        
    def rename_category(self, widget, old_name):

        dialog = Gtk.Window(
            title="Rename Category"
        )

        dialog.set_default_size(
            350,
            150
        )

        dialog.set_transient_for(
            widget.get_root()
        )

        dialog.set_modal(True)

        box = Gtk.Box(
            orientation=Gtk.Orientation.VERTICAL,
            spacing=10
        )

        box.set_margin_top(15)
        box.set_margin_bottom(15)
        box.set_margin_start(15)
        box.set_margin_end(15)

        entry = Gtk.Entry()
        entry.set_text(old_name)

        box.append(entry)

        button_box = Gtk.Box(
            orientation=Gtk.Orientation.HORIZONTAL,
            spacing=10
        )

        button_box.set_halign(Gtk.Align.END)

        cancel_button = Gtk.Button(
            label="Cancel"
        )

        cancel_button.connect(
            "clicked",
            lambda button: dialog.close()
        )

        button_box.append(cancel_button)

        rename_button = Gtk.Button(
            label="Rename"
        )

        button_box.append(rename_button)

        box.append(button_box)

        def do_rename(button):

            new_name = entry.get_text().strip()

            if not new_name:
                return

            if new_name == old_name:
                dialog.close()
                return

            rename_category_db(
                self.db,
                old_name,
                new_name
            )

            manage_window = widget.get_root()

            dialog.close()

            manage_window.close()
            
            self.load_ideas()

            self.manage_categories()

        rename_button.connect(
            "clicked",
            do_rename
        )

        dialog.set_child(box)

        dialog.present()
        
        
    def new_idea(self, button):

        dialog = Gtk.Window()

        dialog.set_title("New Idea")
        dialog.set_default_size(500, 500)

        box = Gtk.Box(
            orientation=Gtk.Orientation.VERTICAL,
            spacing=10
        )

        box.set_margin_top(15)
        box.set_margin_bottom(15)
        box.set_margin_start(15)
        box.set_margin_end(15)

        # Title
        label = Gtk.Label(
            label="Title"
        )

        label.set_xalign(0)

        box.append(label)

        title_entry = Gtk.Entry()

        title_entry.set_placeholder_text(
            "Enter a short title for the idea"
        )

        box.append(title_entry)

        # Category
        label = Gtk.Label(
            label="Category"
        )

        label.set_xalign(0)

        box.append(label)

        category_options = get_categories(self.db)

        category = Gtk.DropDown.new_from_strings(
            category_options
        )

        box.append(category)

        # Status
        label = Gtk.Label(
            label="Status"
        )

        label.set_xalign(0)

        box.append(label)

        status = Gtk.DropDown.new_from_strings([
            "Idea",
            "Considering",
            "Working On",
            "Finished",
            "Abandoned"
        ])

        box.append(status)

        # Notes
        label = Gtk.Label(
            label="Notes"
        )

        label.set_xalign(0)

        box.append(label)

        notes = Gtk.TextView()

        notes.set_wrap_mode(
            Gtk.WrapMode.WORD
        )

        notes.set_vexpand(True)

        box.append(notes)

        # Buttons
        button_box = Gtk.Box(
            orientation=Gtk.Orientation.HORIZONTAL,
            spacing=10
        )

        button_box.set_halign(
            Gtk.Align.END
        )

        cancel_button = Gtk.Button(
            label="Cancel"
        )

        cancel_button.connect(
            "clicked",
            lambda button: dialog.close()
        )

        save_button = Gtk.Button(
            label="Save Idea"
        )

        save_button.connect(
            "clicked",
            lambda button: self.save_idea(
                dialog,
                title_entry,
                category,
                status,
                notes
            )
        )

        button_box.append(cancel_button)
        button_box.append(save_button)

        box.append(button_box)

        dialog.set_child(box)

        dialog.set_transient_for(
            self.get_active_window()
        )

        dialog.present()
        
        categories_button = Gtk.Button(
            label="Manage Categories"
        )

        categories_button.connect(
            "clicked",
            self.manage_categories
        )

    def save_idea(
        self,
        dialog,
        title_entry,
        category,
        status,
        notes
    ):

        title = title_entry.get_text().strip()

        if not title:

            error = Gtk.AlertDialog()

            error.set_message(
                "Please enter a title."
            )

            error.show(dialog)

            return

        # Get notes from TextView
        text_buffer = notes.get_buffer()

        start_iter = text_buffer.get_start_iter()
        end_iter = text_buffer.get_end_iter()

        notes_text = text_buffer.get_text(
            start_iter,
            end_iter,
            False
        )

        category_text = (
            category
            .get_selected_item()
            .get_string()
        )

        status_text = (
            status
            .get_selected_item()
            .get_string()
        )

        now = datetime.now().strftime(
            "%Y-%m-%d %H:%M:%S"
        )

        self.db.execute("""
            INSERT INTO ideas
            (
                title,
                category,
                status,
                notes,
                created_at,
                updated_at
            )
            VALUES (?, ?, ?, ?, ?, ?)
        """, (
            title,
            category_text,
            status_text,
            notes_text,
            now,
            now
        ))

        self.db.commit()

        print("Idea saved.")

        dialog.close()

        self.load_ideas()


app = IdeaBox()
app.run()
