# Copyright (C) 2009 Aaron Bentley <aaron@aaronbentley.com>
#
#    This program 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 2 of the License, or
#    (at your option) any later version.
#
#    This program 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 this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA


import errno

from bzrlib.conflicts import TextConflict
from bzrlib.diff import internal_diff
from bzrlib.workingtree import WorkingTree
from bzrlib.plugins.bzrtools import errors


class ConflictDiffer(object):

    def __init__(self):
        self._old_tree = None
        self._tree = None

    def run(self, output, files=None, direction='other'):
        if files is None:
            self._tree = WorkingTree.open_containing('.')[0]
            files = [self._tree.abspath(c.path) for c in self._tree.conflicts()
                     if isinstance(c, TextConflict)]
        for filename in files:
            self.conflict_diff(output, filename, direction)

    def conflict_diff(self, output, filename, direction):
        """Perform a diff for a file with conflicts."""
        old_path = filename + '.BASE'
        old_lines = self.get_old_lines(filename, old_path)
        new_path_extension = {
            'other': '.OTHER',
            'this': '.THIS'}[direction]
        new_path = filename + new_path_extension
        newlines = open(new_path).readlines()
        internal_diff(old_path, old_lines, new_path, newlines, output)

    def get_old_tree(self, tree, base_path):
        if self._old_tree is not None:
            return self._old_tree
        graph = tree.branch.repository.get_graph()
        parent_ids = tree.get_parent_ids()
        if len(parent_ids) < 2:
            raise errors.NoConflictFiles(base_path)
        lca = graph.find_unique_lca(*parent_ids)
        return tree.branch.repository.revision_tree(lca)

    def get_old_lines(self, filename, base_path):
        """"Return the lines from before the conflicting changes were made."""
        try:
            old_lines = open(base_path).readlines()
        except IOError, e:
            if e.errno != errno.ENOENT:
                raise
            return self.get_base_tree_lines(filename, base_path)
        return old_lines

    def get_base_tree_lines(self, filename, base_path):
        if self._tree is None:
            tree, path = WorkingTree.open_containing(filename)
        else:
            tree = self._tree
            path = tree.relpath(filename)
        tree.lock_read()
        try:
            file_id = tree.path2id(path)
            old_tree = self.get_old_tree(tree, base_path)
            return old_tree.get_file_lines(file_id)
        finally:
            tree.unlock()
