#!/usr/bin/env python3
from pathlib import Path
from subprocess import check_call, check_output
import time
import json
import os
from tempfile import TemporaryDirectory


CONFIG = """

INDEXERS = []

OUTPUT_DIR = {output_dir}

# TODO add dummy indexer
INDEXERS = []

"""


def run_bin(name: str, *args):
    # TODO install binary or something? not sure...
    binary = Path(__file__).absolute().parent.parent / name
    check_call(
        [str(x) for x in [binary, *args]],
        env={'PYTHONPATH': 'src', **os.environ}, # TODO hacky...
    )


def run(tdir: Path):
    cfg = CONFIG.format(output_dir=f'"{tdir}"')
    cfg_file = tdir / 'config.py'
    cfg_file.write_text(cfg)

    run_bin('run', 'index', '--config', cfg_file)
    # TODO (cron env??)

    # TODO uninstall too?
    run_bin(
        'setup_server',
        '--unit-name', 'promnesia-test.service',
        '--db', str(tdir / 'promnesia.sqlite'),
        '--timezone', 'Europe/Moscow',
        '--port', '17777', # TODO get free port?
    )

    response = None
    for x in range(10):
        time.sleep(1)
        try:
            response = json.loads(check_output([
                'curl', 'localhost:17777/status', '--data', '',
            ]).decode('utf8'))
            break
        except Exception as e:
            print(str(e))
    assert response is not None

    response = json.loads(check_output([
        'curl', 'localhost:17777/status', '--data', '',
    ]).decode('utf8'))

    print(response)
    assert response == {
        'status': 'OK',
        'db'    : str(tdir / 'promnesia.sqlite'),
    }

    time.sleep(1)
    check_call([
        'systemctl', '--no-pager', '--user', 'is-active', 'promnesia-test.service',
    ])
    print("Test succeeded!")


def main():
    with TemporaryDirectory() as tdir:
        run(Path(tdir))

if __name__ == '__main__':
    main()
