import StringIO
import dexy.artifact
import dexy.plugin
import logging
import os
import shutil

class Reporter(object):
    TITLE = None
    ALIASES = []
    __metaclass__ = dexy.plugin.PluginMeta

    @classmethod
    def is_active(klass):
        return True

    ALLREPORTS = True # whether to be included in 'allreports', set to false for reporters with side effects
    REPORTS_DIR = None
    SAFETY_FILENAME = ".dexy-generated"
    README_FILENAME = "README"

    @classmethod
    def create_reports_dir(self, reports_dir=None):
        if not reports_dir:
            reports_dir = self.REPORTS_DIR

        self.remove_reports_dir(reports_dir, keep_empty_dir=True)

        safety_filepath = os.path.join(reports_dir, self.SAFETY_FILENAME)
        readme_filepath = os.path.join(reports_dir, self.README_FILENAME)

        if not os.path.exists(reports_dir):
            os.mkdir(reports_dir)

        with open(safety_filepath, "w") as f:
            f.write("""
            This directory was generated by the %s Dexy Reporter and
            may be deleted without notice.\n\n""" % self.__class__.__name__)
        with open(readme_filepath, "w") as f:
            f.write("""
            This directory was generated by the %s Dexy Reporter and
            may be deleted without notice.\n\n""" % self.__class__.__name__)

    @classmethod
    def remove_reports_dir(self, reports_dir=None, keep_empty_dir=False):
        if not reports_dir:
            reports_dir = self.REPORTS_DIR

        if not reports_dir:
            return False

        safety_filepath = os.path.join(reports_dir, self.SAFETY_FILENAME)

        if os.path.exists(reports_dir) and not os.path.exists(safety_filepath):
            raise Exception("Please remove directory %s, Dexy wants to put a report here but doesn't want to overwrite anything by accident." % os.path.abspath(reports_dir))
        elif os.path.exists(reports_dir):
            if keep_empty_dir:
                # Does not remove the base directory, useful if you are running
                # a process (like 'dexy serve') from inside that directory
                for f in os.listdir(reports_dir):
                    path = os.path.join(reports_dir, f)
                    if os.path.isdir(path):
                        shutil.rmtree(path)
                    else:
                        os.remove(path)
            else:
                shutil.rmtree(reports_dir)

    def run(self, wrapper):
        pass

    def set_log(self):
        if not hasattr(self, 'log'):
            self.log = logging.getLogger("report:%s" % self.ALIASES[0])
            self.logstream = StringIO.StringIO()
            handler = logging.StreamHandler(self.logstream)
            if hasattr(self, 'wrapper'):
                handler.setFormatter(logging.Formatter(self.wrapper.log_format))
            self.log.addHandler(handler)
            self.log.setLevel(logging.DEBUG)

            try:
                self.log.addHandler(logging.getLogger('dexy').handlers[0])
            except IndexError:
                pass
