# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

from __future__ import absolute_import, unicode_literals

from abc import (
    ABCMeta,
    abstractmethod,
)

import errno
import os
import time

from contextlib import contextmanager

from mach.mixin.logging import LoggingMixin

import mozpack.path as mozpath
from ..preprocessor import Preprocessor
from ..pythonutil import iter_modules_in_path
from ..util import FileAvoidWrite
from ..frontend.data import (
    ContextDerived,
    ReaderSummary,
)
from .configenvironment import ConfigEnvironment


class BackendConsumeSummary(object):
    """Holds state about what a backend did.

    This is used primarily to print a summary of what the backend did
    so people know what's going on.
    """
    def __init__(self):
        # How many moz.build files were read. This includes included files.
        self.mozbuild_count = 0

        # The number of derived objects from the read moz.build files.
        self.object_count = 0

        # The number of backend files created.
        self.created_count = 0

        # The number of backend files updated.
        self.updated_count = 0

        # The number of unchanged backend files.
        self.unchanged_count = 0

        # The number of deleted backend files.
        self.deleted_count = 0

        # The total wall time this backend spent consuming objects. If
        # the iterable passed into consume() is a generator, this includes the
        # time spent to read moz.build files.
        self.wall_time = 0.0

        # CPU time spent by during the interval captured by wall_time.
        self.cpu_time = 0.0

        # The total wall time spent executing moz.build files. This is just
        # the read and execute time. It does not cover consume time.
        self.mozbuild_execution_time = 0.0

        # The total wall time spent emitting objects from sandboxes.
        self.emitter_execution_time = 0.0

        # The total wall time spent in the backend. This counts the time the
        # backend writes out files, etc.
        self.backend_execution_time = 0.0

        # How much wall time the system spent doing other things. This is
        # wall_time - mozbuild_execution_time - emitter_execution_time -
        # backend_execution_time.
        self.other_time = 0.0

        # Mapping of changed file paths to diffs of the changes.
        self.file_diffs = {}

    @property
    def reader_summary(self):
        return 'Finished reading {:d} moz.build files in {:.2f}s'.format(
            self.mozbuild_count,
            self.mozbuild_execution_time)

    @property
    def emitter_summary(self):
        return 'Processed into {:d} build config descriptors in {:.2f}s'.format(
            self.object_count, self.emitter_execution_time)

    @property
    def backend_summary(self):
        return 'Backend executed in {:.2f}s'.format(self.backend_execution_time)

    def backend_detailed_summary(self):
        """Backend summary to be supplied by BuildBackend implementations."""
        return None

    @property
    def total_summary(self):
        efficiency_value = self.cpu_time / self.wall_time if self.wall_time else 100
        return 'Total wall time: {:.2f}s; CPU time: {:.2f}s; Efficiency: ' \
            '{:.0%}; Untracked: {:.2f}s'.format(
                self.wall_time, self.cpu_time, efficiency_value,
                self.other_time)

    def summaries(self):
        yield self.reader_summary
        yield self.emitter_summary
        yield self.backend_summary

        detailed = self.backend_detailed_summary()
        if detailed:
            yield detailed

        yield self.total_summary


class BuildBackend(LoggingMixin):
    """Abstract base class for build backends.

    A build backend is merely a consumer of the build configuration (the output
    of the frontend processing). It does something with said data. What exactly
    is the discretion of the specific implementation.
    """

    __metaclass__ = ABCMeta

    def __init__(self, environment):
        assert isinstance(environment, ConfigEnvironment)

        self.populate_logger()

        self.environment = environment
        self.summary = BackendConsumeSummary()

        # Files whose modification should cause a new read and backend
        # generation.
        self.backend_input_files = set()

        # Files generated by the backend.
        self._backend_output_files = set()

        # Previously generated files.
        self._backend_output_list_file = mozpath.join(environment.topobjdir,
            'backend.%s' % self.__class__.__name__)
        self._backend_output_list = set()
        if os.path.exists(self._backend_output_list_file):
            l = open(self._backend_output_list_file).read().split('\n')
            self._backend_output_list.update(mozpath.normsep(p) for p in l)

        self._environments = {}
        self._environments[environment.topobjdir] = environment

        self._init()

    def _init():
        """Hook point for child classes to perform actions during __init__.

        This exists so child classes don't need to implement __init__.
        """

    def consume(self, objs):
        """Consume a stream of TreeMetadata instances.

        This is the main method of the interface. This is what takes the
        frontend output and does something with it.

        Child classes are not expected to implement this method. Instead, the
        base class consumes objects and calls methods (possibly) implemented by
        child classes.
        """
        cpu_start = time.clock()
        time_start = time.time()
        backend_time = 0.0

        for obj in objs:
            self.summary.object_count += 1
            obj_start = time.time()
            self.consume_object(obj)
            backend_time += time.time() - obj_start

            if isinstance(obj, ContextDerived):
                self.backend_input_files |= obj.context_all_paths

            if isinstance(obj, ReaderSummary):
                self.summary.mozbuild_count = obj.total_file_count
                self.summary.mozbuild_execution_time = obj.total_sandbox_execution_time
                self.summary.emitter_execution_time = obj.total_emitter_execution_time

        # Pull in all loaded Python as dependencies so any Python changes that
        # could influence our output result in a rescan.
        self.backend_input_files |= set(iter_modules_in_path(
            self.environment.topsrcdir, self.environment.topobjdir))

        finished_start = time.time()
        self.consume_finished()
        backend_time += time.time() - finished_start

        # Purge backend files created in previous run, but not created anymore
        delete_files = self._backend_output_list - self._backend_output_files
        for path in delete_files:
            try:
                os.unlink(mozpath.join(self.environment.topobjdir, path))
                self.summary.deleted_count += 1
            except OSError:
                pass
        # Remove now empty directories
        for dir in set(mozpath.dirname(d) for d in delete_files):
            try:
                os.removedirs(dir)
            except OSError:
                pass

        # Write out the list of backend files generated, if it changed.
        if self.summary.deleted_count or self.summary.created_count or \
                not os.path.exists(self._backend_output_list_file):
            with open(self._backend_output_list_file, 'w') as fh:
                fh.write('\n'.join(sorted(self._backend_output_files)))
        elif self.summary.updated_count:
            with open(self._backend_output_list_file, 'a'):
                os.utime(self._backend_output_list_file, None)

        self.summary.cpu_time = time.clock() - cpu_start
        self.summary.wall_time = time.time() - time_start
        self.summary.backend_execution_time = backend_time
        self.summary.other_time = self.summary.wall_time - \
            self.summary.mozbuild_execution_time - \
            self.summary.emitter_execution_time - \
            self.summary.backend_execution_time

        return self.summary

    @abstractmethod
    def consume_object(self, obj):
        """Consumes an individual TreeMetadata instance.

        This is the main method used by child classes to react to build
        metadata.
        """

    def consume_finished(self):
        """Called when consume() has completed handling all objects."""

    @contextmanager
    def _write_file(self, path=None, fh=None):
        """Context manager to write a file.

        This is a glorified wrapper around FileAvoidWrite with integration to
        update the BackendConsumeSummary on this instance.

        Example usage:

            with self._write_file('foo.txt') as fh:
                fh.write('hello world')
        """

        if path is not None:
            assert fh is None
            fh = FileAvoidWrite(path, capture_diff=True)
        else:
            assert fh is not None

        dirname = mozpath.dirname(fh.name)
        try:
            os.makedirs(dirname)
        except OSError as error:
            if error.errno != errno.EEXIST:
                raise

        yield fh

        self._backend_output_files.add(mozpath.relpath(fh.name, self.environment.topobjdir))
        existed, updated = fh.close()
        if not existed:
            self.summary.created_count += 1
        elif updated:
            self.summary.updated_count += 1
            if fh.diff:
                self.summary.file_diffs[fh.name] = fh.diff
        else:
            self.summary.unchanged_count += 1

    @contextmanager
    def _get_preprocessor(self, obj):
        '''Returns a preprocessor with a few predefined values depending on
        the given BaseConfigSubstitution(-like) object, and all the substs
        in the current environment.'''
        pp = Preprocessor()
        srcdir = mozpath.dirname(obj.input_path)
        pp.context.update(obj.config.substs)
        pp.context.update(
            top_srcdir=obj.topsrcdir,
            srcdir=srcdir,
            relativesrcdir=mozpath.relpath(srcdir, obj.topsrcdir) or '.',
            DEPTH=mozpath.relpath(obj.topobjdir, mozpath.dirname(obj.output_path)) or '.',
        )
        pp.do_filter('attemptSubstitution')
        pp.setMarker(None)
        with self._write_file(obj.output_path) as fh:
            pp.out = fh
            yield pp
