""" turtle compare plugin for nautilus

This file is part of Turtle.

Turtle is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Turtle is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Turtle. If not, see <https://www.gnu.org/licenses/>. 
"""
import os
import gi
import subprocess
import turtlevcs
gi.require_version("Gtk", "4.0")
from gi.repository import Nautilus, GObject


class TurtleCompareMenuProvider(GObject.GObject, Nautilus.MenuProvider):
    """ compare menu provider class for nautilus """

    settings = None
    left = None

    def _create_menu_item(self, name, label, tip="", icon=""):
        item = Nautilus.MenuItem(
            name=name,
            label=label,
            tip=tip,
            icon=icon)

        return item

    def _menu_compare_left_cb(self, menu, file):
        self.left = file

    def _menu_compare_right_cb(self, menu, file):
        left = self.left
        self.left = None
        subprocess.Popen(["meld", left, file])

    def _menu_compare_cb(self, menu, file1, file2):
        self.left = None
        subprocess.Popen(["meld", file1, file2])

    def get_file_items(self, files):
        """ get_file_items from Nautilus.MenuProvider """
        items = []

        if self.settings is None:
            self.settings = turtlevcs.get_settings()

        if self.settings.get_boolean("show-compare"):
            if len(files) == 1:
                file = files[0].get_location().get_path()
                item = self._create_menu_item(
                    "TurtleCompareMenuProvider::CompareLeft", "Compare later...")
                item.connect('activate', self._menu_compare_left_cb, file)
                items.append(item)

                if self.left is not None:
                    item = self._create_menu_item(
                        "TurtleCompareMenuProvider::CompareRight", f"Compare to {self.left}...")
                    item.connect('activate', self._menu_compare_right_cb, file)
                    items.append(item)

            elif len(files) == 2:
                file1 = files[0].get_location().get_path()
                file2 = files[1].get_location().get_path()

                item = self._create_menu_item(
                    "TurtleCompareMenuProvider::Compare", "Compare files...")
                item.connect('activate', self._menu_compare_cb, file1, file2)

                items.append(item)

        return items
