import tempfile

from webtest import Upload

from docbow_project.docbow.models import FileType

MEDIA_ROOT = tempfile.mkdtemp()


def assert_can_see_doc(app, doc, user, inbox=True, trash=False):
    app.login(user.username)
    box_url = '/%s/' % ('inbox' if inbox else 'outbox')
    doc_url = box_url + '%s/' % doc.pk
    if trash:
        box_url += 'trash/'
    resp = app.get(box_url)
    assert 'data-id="%s"' % doc.pk in resp.text
    resp = app.get(doc_url)
    assert resp.status_code == 200
    app.logout()


def assert_cannot_see_doc(app, doc, user, inbox=True):
    app.login(user.username)
    box_url = '/%s/' % ('inbox' if inbox else 'outbox')
    doc_url = box_url + '%s/' % doc.pk
    resp = app.get(box_url)
    assert doc_url not in resp.text
    resp = app.get(doc_url)
    assert resp.status_code == 302
    app.logout()


def send_file(app, settings, sender, recipients, private=False):
    settings.MEDIA_ROOT = MEDIA_ROOT

    try:
        real_recipients = ['user-%s' % r.pk for r in recipients]
    except TypeError:
        real_recipients = ['user-%s' % recipients.pk]

    ft = FileType.objects.first()
    app.login(username=sender.username)
    resp = app.get('/send_file/%s/' % ft.pk)
    form = resp.form
    form['content_1'] = Upload('readme.rst', b'data')
    form['recipients'] = real_recipients
    form['private'] = private
    resp = form.submit('send')
    assert resp.status_code == 302
    assert resp.location.endswith('/outbox/')
    app.logout()
