#!/usr/bin/python
"""
A wrapper script that will split up a p4 file with merge conflicts to three
files and invoke xxdiff on it.
"""

# stdlib imports
import sys, os, shutil, re, StringIO, tempfile

# xxdiff imports
from xxdiff import invoke


def unmerge_file(filename):
    file_original = tempfile.NamedTemporaryFile()
    file_theirs = tempfile.NamedTemporaryFile()
    file_yours = tempfile.NamedTemporaryFile()
    files = file_original, file_theirs, file_yours
    file_current = None
    for line in open(filename):
        if line.startswith('>>>> ORIGINAL'):
            file_current = file_original
        elif line.startswith('==== THEIRS'):
            file_current = file_theirs
        elif line.startswith('==== YOURS'):
            file_current = file_yours
        elif line.startswith('<<<<'):
            file_current = None
        elif file_current is None:
            for file_ in files:
                file_.write(line)
        else:
            file_current.write(line)
    for file_ in files:
        file_.flush()
    return files


def main():
    import optparse
    parser = optparse.OptionParser(__doc__.strip())
    invoke.options_graft(parser)
    opts, args = parser.parse_args()
    invoke.options_validate(opts, parser)

    if len(args) != 1:
        parser.error("You need to provide 1 file argumnet.")
    filename, = args

    file_original, file_theirs, file_yours = unmerge_file(filename)


    # Invoke xxdiff.
    decision, mergedf, __retcode = invoke.xxdiff_decision(
        opts,
        '--merged-filename=%s' % filename,
        '--title1=Current',
        '--title2=Ancestor',
        '--title3=Merging',
        file_yours.name, file_original.name, file_theirs.name)


if __name__ == '__main__':
    sys.exit(main())
