import cattle
import os
import pytest
import random
import time
from datetime import datetime, timedelta


NOT_NONE = object()
DEFAULT_TIMEOUT = 90
DEFAULT_AGENT_URI = 'ssh://root@localhost:22'
DEFAULT_AGENT_UUID = 'test-agent'
SLEEP_DELAY = 0.5


@pytest.fixture(scope='session')
def cattle_url():
    default_url = 'http://localhost:8080/v1/schemas'
    return os.environ.get('CATTLE_URL', default_url)


def _admin_client():
    return cattle.from_env(url=cattle_url(),
                           cache=False,
                           access_key='admin',
                           secrect_key='adminpass')


def _client_for_user(name, accounts):
    return cattle.from_env(url=cattle_url(),
                           cache=False,
                           access_key=accounts[name][0],
                           secret_key=accounts[name][1])


def create_user(admin_client, user_name, kind=None):
    if kind is None:
        kind = user_name

    password = user_name + 'pass'
    account = create_type_by_uuid(admin_client, 'account', user_name,
                                  kind=user_name,
                                  name=user_name)

    active_cred = None
    for cred in account.credentials():
        if cred.kind == 'apiKey' and cred.publicValue == user_name \
                and cred.secretValue == password:
            active_cred = cred
            break

    if active_cred is None:
        active_cred = admin_client.create_credential({
            'accountId': account.id,
            'kind': 'apiKey',
            'publicValue': user_name,
            'secretValue': password
        })

    active_cred = wait_success(admin_client, active_cred)
    if active_cred.state != 'active':
        wait_success(admin_client, active_cred.activate())

    return [user_name, password, account]


@pytest.fixture(scope='session')
def accounts():
    result = {}
    admin_client = _admin_client()
    for user_name in ['admin', 'agent', 'user', 'agentRegister', 'test',
                      'readAdmin', 'token']:
        result[user_name] = create_user(admin_client,
                                        user_name,
                                        kind=user_name)

    result['admin'] = create_user(admin_client, 'admin')
    system_account = admin_client.list_account(kind='system', uuid='system')[0]
    result['system'] = [None, None, system_account]

    return result


@pytest.fixture(scope='session')
def system_account(accounts):
    return accounts['system'][2]


@pytest.fixture(scope='session')
def admin_account(accounts):
    return accounts['admin'][2]


@pytest.fixture(scope='session')
def client(accounts):
    return _client_for_user('user', accounts)


@pytest.fixture(scope='session')
def admin_client(accounts):
    return _client_for_user('admin', accounts)