from gettext import gettext as _
from gi.repository import Gtk, Gdk, Pango
from os import remove, rename
from os.path import getmtime as get_last_modified
from os.path import dirname, isfile
from notorious.confManager import ConfManager


class FileListboxRow(Gtk.ListBoxRow):
    def __init__(self, name, file_path, file_manager, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.confman = ConfManager()

        self.name = name
        self.file_path = file_path
        self.file_manager = file_manager
        self.search_entry = self.file_manager.search_entry
        self.source_view = self.file_manager.source_view
        # this is a unix timestamp
        self.last_modified = get_last_modified(self.file_path)

        self.name_label = Gtk.Label(self.name)
        self.name_label.set_hexpand(False)
        self.name_label.set_halign(Gtk.Align.START)
        self.name_label.set_margin_top(6)
        self.name_label.set_margin_bottom(6)
        self.name_label.set_margin_start(12)
        self.name_label.set_margin_end(12)
        self.name_label.set_ellipsize(
            Pango.EllipsizeMode.END
        )
        self.add(self.name_label)

        self.rename_popover_builder = Gtk.Builder.new_from_resource(
            '/org/gabmus/notorious/ui/rename_popover.glade'
        )
        self.rename_popover = self.rename_popover_builder.get_object('popover')
        self.rename_popover.set_relative_to(self)
        self.rename_entry = self.rename_popover_builder.get_object(
            'rename_entry'
        )
        self.rename_error_revealer = self.rename_popover_builder.get_object(
            'error_revealer'
        )
        self.rename_entry.connect(
            'activate',
            self.on_rename_done
        )
        self.rename_entry.connect(
            'changed',
            self.on_rename_entry_changed
        )
        self.rename_confirm_btn = self.rename_popover_builder.get_object(
            'rename_confirm_btn'
        )
        self.rename_confirm_btn.connect('clicked', self.on_rename_done)

        self.connect(
            'key-press-event',
            self.on_key_press_event
        )

    def on_rename_entry_changed(self, *args):
        self.rename_error_revealer.set_reveal_child(False)

    def on_rename(self, *args):
        self.rename_entry.set_text(self.name)
        self.rename_popover.popup()

    def on_rename_done(self, *args):
        new_filename = self.rename_entry.get_text() + (
            '.md' if self.confman.conf['use_file_extension'] else ''
        )
        new_filepath = f'{dirname(self.file_path)}/{new_filename}'
        if isfile(new_filepath):
            self.rename_error_revealer.set_reveal_child(True)
            return
        self.rename_entry.set_text('')
        rename(
            self.file_path,
            new_filepath
        )
        self.rename_popover.popdown()
        self.confman.emit('notes_dir_changed', '')

    def on_delete(self, *args):
        dialog = Gtk.MessageDialog(
            self.get_toplevel(),
            Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT,
            Gtk.MessageType.QUESTION,
            Gtk.ButtonsType.YES_NO,
            _(
                'Delete note {0}?'
            ).format(
                self.name
            )
        )
        if dialog.run() == Gtk.ResponseType.YES:
            remove(self.file_path)
            self.confman.emit('notes_dir_changed', '')
            if self.file_path == self.file_manager.currently_open_file:
                self.source_view.get_buffer().set_text('')
                self.search_entry.grab_focus()
                self.source_view.set_sensitive(False)
        dialog.close()

    def on_key_press_event(self, widget, event):
        if event.keyval in (Gdk.KEY_Delete, Gdk.KEY_BackSpace):
            self.on_delete()
        elif event.keyval == Gdk.KEY_Escape:
            self.search_entry.grab_focus()
        elif event.keyval == Gdk.KEY_F2:
            self.on_rename()
