import functools
import os
import pytest

from tortoisehg.hgqt import filedata, thgrepo

import helpers

def setup_module():
    global _tmpdir
    _tmpdir = helpers.mktmpdir(__name__)

    hg = helpers.HgClient(os.path.join(_tmpdir, b'status'))
    hg.init()
    hg.fwrite(b'.hg/hgrc', b'[tortoisehg]\nmaxdiff = 1\n')  # 1kB

    hg.fwrite(b'text', b'foo\n')
    hg.fwrite(b'binary', b'\0')
    hg.fwrite(b'text-over1kb', (b'a' * 63 + b'\n') * 16 + b'\n')
    hg.commit(b'-Am', b'add')

    paths = [b'text', b'binary', b'text-over1kb']
    for p in paths:
        hg.copy(p, p + b'.copied')
    hg.commit(b'-m', b'copy')

    for p in paths:
        hg.rename(p, p + b'.renamed')
    hg.commit(b'-m', b'rename')

def loaddata(reponame, rev, path, prev=None):
    # thgrepository extension is necessary because of repo.maxdiff
    repo = thgrepo.repository(path=os.path.join(_tmpdir, reponame))
    ctx = repo[rev]
    if prev is None:
        pctx = ctx.p1()
    else:
        pctx = repo[prev]
    fd = filedata.createFileData(ctx, pctx, path)
    fd.load()
    return fd


@pytest.mark.parametrize('get_fd, message', [
    (functools.partial(loaddata, b'status', rev, path + sfx), msg)
    for rev, sfx in [(0, b''), (1, b'.copied'), (2, b'.renamed')]
    for path, msg in [(b'binary', 'is binary'),
                      (b'text-over1kb', 'is larger than')]
])
def test_error_added(get_fd, message):
    fd = get_fd()
    assert message in fd.error, (message, fd.error)
    # no data should be loaded
    assert not fd.contents
    assert not fd.olddata
    assert not fd.diff

def check_flabel(fd, message):
    assert message in fd.flabel, (message, fd.flabel)

@pytest.mark.parametrize('get_fd, message', [
    (functools.partial(loaddata, b'status', rev, path + sfx), msg)
    for path in [b'text', b'binary', b'text-over1kb']
    for rev, sfx, msg in [(0, b'', 'added'),
                          (1, b'.copied', 'copied from'),
                          (2, b'.renamed', 'renamed from')]
])
def test_flabel_added(get_fd, message):
    check_flabel(get_fd(), message)

def test_flabel_far_rename():
    fd = loaddata(b'status', 2, b'text.copied', 0)
    check_flabel(fd, 'renamed from')  # source 'text' is removed at rev 2
