# This is a sample commands.py.  You can add your own commands here.
#
# Please refer to commands_full.py for all the default commands and a complete
# documentation.  Do NOT add them all here, or you may end up with defunct
# commands when upgrading ranger.

# You always need to import ranger.api.commands here to get the Command class:
from ranger.api.commands import *

# A simple command for demonstration purposes follows.
#------------------------------------------------------------------------------

# You can import any python module as needed.
import os
from subprocess import Popen, PIPE, STDOUT

# Any class that is a subclass of "Command" will be integrated into ranger as a
# command.  Try typing ":my_edit<ENTER>" in ranger!
class my_edit(Command):
    # The so-called doc-string of the class will be visible in the built-in
    # help that is accessible by typing "?c" inside ranger.
    """:my_edit <filename>

    A sample command for demonstration purposes that opens a file in an editor.
    """

    # The execute method is called when you run this command in ranger.
    def execute(self):
        # self.arg(1) is the first (space-separated) argument to the function.
        # This way you can write ":my_edit somefilename<ENTER>".
        if self.arg(1):
            # self.rest(1) contains self.arg(1) and everything that follows
            target_filename = self.rest(1)
        else:
            # self.fm is a ranger.core.filemanager.FileManager object and gives
            # you access to internals of ranger.
            # self.fm.thisfile is a ranger.container.file.File object and is a
            # reference to the currently selected file.
            target_filename = self.fm.thisfile.path

        # This is a generic function to print text in ranger.  
        self.fm.notify("Let's edit the file " + target_filename + "!")

        # Using bad=True in fm.notify allows you to print error messages:
        if not os.path.exists(target_filename):
            self.fm.notify("The given file does not exist!", bad=True)
            return

        # This executes a function from ranger.core.acitons, a module with a
        # variety of subroutines that can help you construct commands.
        # Check out the source, or run "pydoc ranger.core.actions" for a list.
        self.fm.edit_file(target_filename)

    # The tab method is called when you press tab, and should return a list of
    # suggestions that the user will tab through.
    def tab(self):
        # This is a generic tab-completion function that iterates through the
        # content of the current directory.
        return self._tab_directory_content()


class tmsu_tag(Command):
    """:tmsu_tag <tags>

    Add one or more tmsu tags to the current selections.
    """
    def execute(self):
        files = ""
        for file in self.fm.thistab.get_selection():
            files += "'" + file.path + "' "
        self.fm.execute_console("shell tmsu tag --tags='" + self.rest(1) + "' " + files)
        return


class tmsu_untag(Command):
    """:tmsu_untag <tags>

    Remove one or more tags from the current selection.
    """
    def execute(self):
        files = ""
        for file in self.fm.thistab.get_selection():
            files += "'" + file.path + "' "
        self.fm.execute_console("shell tmsu untag --tags='" + self.rest(1) + "' " + files)
        return


class tmsu_list_tags(Command):
    """:tmsu_list_tags

    List tags for the current file.
    """
    def execute(self):
        cmd = "tmsu tags '" + self.fm.thisfile.path + "'"
        p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
        output = p.stdout.read().decode("utf-8").split(': ', 1)

        if len(output) == 1:
            self.fm.notify("File has no tags.")
        else:
            self.fm.notify("Tags: " + output[1])
        return


class tmsu_imply(Command):
    """:tmsu_imply <tag1> <tag2>

    Create a tag implication such that any file tagged <tag1> will be
    implicitly tagged <tag2>.
    """
    def execute(self):
        tag1 = self.arg(1)
        tag2 = self.arg(2)
        self.fm.execute_console("shell tmsu imply %s %s" % (tag1, tag2))
        return


class tmsu_merge(Command):
    """:tmsu_merge <tag> [<tag>...] <dest>

    Merges <tags>(s) into tag <dest> resulting in a single tag of name <dest>.

    """
    def execute(self):
        self.fm.execute_console("shell tmsu merge %s" % (self.rest(1)))
        return
