import os

import deltachat
import pytest
import requests


@pytest.fixture
def tmp_file_path(tmpdir):
    path = str(tmpdir) + "/testfile"
    with open(path, "w+", encoding="utf-8") as f:
        f.write("test")
    return path


@pytest.fixture
def chat(tmpdir):
    token = os.getenv("DCC_NEW_TMP_EMAIL", "https://nine.testrun.org/cgi-bin/newemail.py")

    # create bot account from token
    result = requests.post(token)
    addr = result.json()['email']
    password = result.json()['password']
    bot = deltachat.Account(str(tmpdir) + "/db.sqlite")
    bot.run_account(addr=addr, password=password, show_ffi=True)
    # :TODO how to start the loop? In a subthread?

    # create chat partner from token
    result = requests.post(token)
    addr = result.json()['email']
    password = result.json()['password']
    user = deltachat.Account(str(tmpdir) + "/db.sqlite")
    user.run_account(addr=addr, password=password, show_ffi=False)

    # initiate a chat between them
    yield user.create_chat(bot.get_config('addr'))
    # return the chat object
    bot.shutdown()
    user.shutdown()
    bot.wait_shutdown()
    user.wait_shutdown()