import pytest
import requests_cache

from favro_sync import secrets
from favro_sync.favro_client import FavroClient, OrganizationId, SeqId

needs_secrets = pytest.mark.skipif(
    not secrets.has_secrets(),
    reason='Secrets required',
)


@needs_secrets
def test_create_client():
    client = create_client()
    assert client is not None
    client.check_logged_in()


@needs_secrets
def test_get_card():
    client = create_client()
    card = client.get_card(SeqId(11368))

    assert_valid_card(card)

    assert card.detailed_description is not None
    assert len(card.dependencies) == 1
    assert len(card.attachments) == 0
    assert len(card.custom_fields) == 2


@needs_secrets
def test_get_archived_card():
    client = create_client()
    card = client.get_card(SeqId(8723))
    assert card.is_archived


@needs_secrets
def test_get_card_with_color_custom_field():
    client = create_client()
    card = client.get_card(SeqId(8779))
    assert len(card.custom_fields) > 0


@needs_secrets
def test_get_cards():
    client = create_client()
    for card in client.get_cards(todo_list=True):
        assert_valid_card(card)


@needs_secrets
def test_get_collections():
    client = create_client()
    for collection in client.get_collections():
        print(collection)
        assert collection.collection_id is not None
        assert collection.organization_id is not None
        assert collection.name is not None
        assert collection.background is not None
        assert collection.is_archived is not None
        assert collection.widget_common_id is None


def create_client():
    session = requests_cache.CachedSession('output/test-http-cache.sqlite')
    return FavroClient(
        favro_org_id=OrganizationId(secrets.favro_org_id()),
        favro_username=secrets.favro_username(),
        favro_password=secrets.favro_password(),
        read_only=True,
        session=session,
    )


def assert_valid_card(card):
    assert card is not None
    assert card.name is not None
    assert card.is_archived is not None