#!/usr/local/bin/python
# encoding: utf-8
"""
*sorts the contents of all taskpaper files via workflow tags*

:Author:
    David Young

:Date Created:
    November  5, 2016
"""
################# GLOBAL IMPORTS ####################
import sys
import os
os.environ['TERM'] = 'vt100'
from fundamentals import tools
from fundamentals.renderer import list_of_dictionaries
from operator import itemgetter
import collections
import codecs
import textwrap
from tastic.tastic import document


class workspace():
    """
    *tools for sorting, archiving and indexing tasks and maintaining the contents of all taskpaper files within a given workspace*

    **Key Arguments:**
        - ``log`` -- logger
        - ``fileOrWorkspacePath`` -- the root path of the workspace you wish to sort the taskpaper docs within, or the path to a single taskpaper file
        - ``settings`` -- the settings dictionary

    **Usage:**

        To setup your logger, settings and database connections, please use the ``fundamentals`` package (`see tutorial here <http://fundamentals.readthedocs.io/en/latest/#tutorial>`_). 

        To initiate a taskpaper workspace object, use the following:

        .. code-block:: python 

            from tastic.workspace import workspace
            ws = workspace(
                log=log,
                settings=settings,
                fileOrWorkspacePath="/path/to/root/of/workspace"
            )

        or to target a single taskpaper document use instead the path to the file:

        .. code-block:: python 

            from tastic.workspace import workspace
            ws = workspace(
                log=log,
                settings=settings,
                fileOrWorkspacePath="/path/to/doc.taskpaper"
            )
    """
    # Initialisation

    def __init__(
            self,
            log,
            fileOrWorkspacePath,
            settings=False
    ):
        self.log = log
        log.debug("instansiating a new 'sort' object")
        self.settings = settings
        self.taskpaperPath = False
        self.workspaceRoot = False
        # xt-self-arg-tmpx

        # INITIAL ACTIONS
        # ARE WE DEALING WITH A WORKSPACE DIRECTORY OR SINGLE FILE
        if os.path.isfile(fileOrWorkspacePath):
            self.taskpaperPath = fileOrWorkspacePath
        else:
            self.workspaceRoot = fileOrWorkspacePath

        self.taskpaperFiles = self._get_all_taskpaper_files()

        return None

    def sort(self):
        """
        *sort the workspace or individual taskpaper document via the workflow tags found in the settings file*

        **Usage:**

            To sort all of the taskpaper documents in the workspace via the workflow tag set with the settings file, for example:

            .. code-block:: yaml

                workflowTags: "@due, @flag, @hold, @next, @someday, @wait" 

            use the ``sort()`` method:

            .. code-block:: python 

                ws.sort()
        """
        self.log.info('starting the ``sort`` method')

        for f in self.taskpaperFiles:
            self._sort_tp_file(f)

        self.log.info('completed the ``sort`` method')
        return None

    def archive_done(
            self):
        """*move done tasks from the document's 'Archive' project into an adjacent markdown tasklog file*

        **Usage:**

            To move the archived tasks within a workspace's taskpaper docs into ``-tasklog.md`` files use the ``archive_done()`` method:

            .. code-block:: python 

                ws.archive_done()
        """
        self.log.info('starting the ``archive_done`` method')

        for f in self.taskpaperFiles:
            self._archive_tp_file_done_tasks(f)

        self.log.info('completed the ``archive_done`` method')
        return None

    def _get_all_taskpaper_files(
            self):
        """*get a list of all the taskpaper filepaths in the workspace*

        **Return:**
            - ``taskpaperFiles`` -- a list of paths to all the taskpaper files within the workspace
        """
        self.log.info('starting the ``_get_all_taskpaper_files`` method')

        if self.workspaceRoot:
            from fundamentals.files import recursive_directory_listing