from yaml import load, SafeLoader
from os import environ
from mookdns import MookDns

from vaultwarden import VaultWarden


def test_vaultwarden_login():
    conf_file = f'{environ["MACHINE_TEST_DIR"]}/vaultwarden.yml'
    with open(conf_file) as yaml:
        data = load(yaml, Loader=SafeLoader)
    with MookDns(data['revprox_ip']):
        vaultwarden = VaultWarden(data['url'], data['username'], data['uuid'], data['privkey'])
        if 'FIRST_RUN' in environ:
            vaultwarden.register(data['password'])
        vaultwarden.login(data['password'])
        vaultwarden.load_organizations()


def test_vaultwarden_collection():
    conf_file = f'{environ["MACHINE_TEST_DIR"]}/vaultwarden.yml'
    with open(conf_file) as yaml:
        data = load(yaml, Loader=SafeLoader)
    with MookDns(data['revprox_ip']):
        vaultwarden = VaultWarden(data['url'], data['username'], data['uuid'], data['privkey'])
        vaultwarden.login(data['password'])
        vaultwarden.load_organizations()
        if 'FIRST_RUN' in environ:
            organization_id = vaultwarden.create_organization(data['username'],
                                                              'test_organization',
                                                              )
            vaultwarden.create_collection(organization_id,
                                          'test_collection',
                                          )
    assert len(vaultwarden.vaultwarden_organizations) == 2
    for org in vaultwarden.vaultwarden_organizations:
        if org is not None:
            assert vaultwarden.vaultwarden_organizations[org]['name'] == 'test_organization'
            assert len(vaultwarden.vaultwarden_organizations[org]['collections']) == 2
            assert set(vaultwarden.vaultwarden_organizations[org]['collections']) == {'test_organization', 'test_collection'}
