import datetime
import os
import sqlite3
import unittest.mock
from unittest.mock import Mock

import pytest

from gitubuntu.importer_service import ImportRequest
import gitubuntu.importer_service as target


# Shortcuts for accessing some enumeration values
REIMPORT = target.ImportRequest.Level.REIMPORT
INCREMENTAL = target.ImportRequest.Level.INCREMENTAL


@pytest.fixture
def state():
    return target.State(':memory:')


def inject_import_request(state, timestamp, reimport, status='needed'):
    """Inject a request into a state instance's database

    Since we haven't implemented requesting reimport via the API, this function
    allows us to do that for test purposes. It also supports incremental
    imports so that we can unify the two cases for easier test parametrization.

    :param target.State state: the state instance
    :param timestamp: the timestamp of the request. This may be a float or an
        integer.
    :param bool reimport: if True, this is a reimport request; False means an
        incremental import.
    :returns: None
    """
    cursor = state.db.cursor()
    cursor.execute(
        '''INSERT INTO request
            (srcpkg, timestamp, status, priority, reimport)
            VALUES ('a', ?, ?, 20, ?)''',
        (timestamp, status, bool(reimport))
    )
    # No need to commit for our tests in general


def test_can_instantiate_state():
    target.State(':memory:')


def test_state_persists(tmpdir):
    state_path = os.path.join(tmpdir, 'db')
    state = target.State(state_path)
    state._write_timestamps({
        'debian': target.Timestamp(time=4, link=None),
        'ubuntu': target.Timestamp(time=4, link=None),
    })
    state = target.State(state_path)
    assert state.read_timestamps(0)['debian'].time == 4


def test_default_timestamp(state):
    assert all([
        state.read_timestamps(2, current_time=1000000)[distro].time == 827200
        for distro in ['debian', 'ubuntu']
    ])


def test_empty_dump_request(state):
    assert state._dump_request() == set()


def test_request_imports(state):
    state.request_imports(['a'], request_time=1)
    assert state._dump_request() == set([('a', 1, 'needed', 20, 0)])


def test_request_imports_updates_timestamps(state):
    timestamps = {
        'debian': target.Timestamp(time=1, link=None),
        'ubuntu': target.Timestamp(time=2, link=None),
    }
    state.request_imports(
        ['a'],
        request_time=1,
        timestamps=timestamps,
    )
    assert state.read_timestamps() == timestamps


@pytest.mark.parametrize(['request_list', 'expected_result'], [
    # incremental import -> request one incremental import
    ([(0, 'needed')], [ImportRequest('a', INCREMENTAL)]),
    # reimport -> request one reimport
    ([(1, 'needed')], [ImportRequest('a', REIMPORT)]),
    # incremental then reimport -> request the reimport
    ([(0, 'needed'), (1, 'needed')], [ImportRequest('a', REIMPORT)]),
    # reimport then incremental -> request the reimport
    ([(1, 'needed'), (0, 'needed')], [ImportRequest('a', REIMPORT)]),
    # incremental already running then reimport -> nothing
    ([(0, 'running'), (1, 'needed')], []),
    # reimport already running then incremental -> nothing
    ([(0, 'needed'), (1, 'running')], []),
])
def test_get_pending_imports(state, request_list, expected_result):
    """State.get_pending_imports() should behave correctly

    :param target.State state: our pytest fixture that provides a target.State
        instance to test.
    :param list(tuple(int, str)) request_list: for each monotonic pretend clock
        tick, whether a request at that time is for a reimport or an
        incremental import and the status of the request. 0 means incremental;
        1 means reimport, as mapped to the database reimport column. The status
        is mapped directly to the database status column.
    :param ImportRequest expected_result: the expected sole entry of the
        returned list of the get_pending_imports() method.
    """
    for timestamp, (reimport, needed) in enumerate(request_list):
        inject_import_request(state, timestamp, reimport, needed)
    state._normalize(state.db)
    assert list(state.get_pending_imports()) == expected_result


def test_completed_request_removed_successfully(state):
    """A completed request should be removed from the database

    :param target.State state: our pytest fixture that provides a target.State
        instance to test.
    """
    state.request_imports(['a', 'b'], request_time=1)
    state.mark_import_outcomes(
        reckoning_time=2,
        completed_requests=[ImportRequest('a', INCREMENTAL)],
        failed_requests=[],
    )
    assert state._dump_request() == set([
        ('b', 1.0, 'needed', 20, 0),
    ])
    state._normalize(state.db, assert_no_action=True)


@pytest.mark.parametrize([
        'request_list',
        'reckoning_time',
        'level',
        'expected_result',
], [
    ([0, 1], 1, REIMPORT, {('a', 1.0, 'needed', 20, 1)}),
    ([0, 1], 2, REIMPORT, set()),
    ([1, 0], 1, REIMPORT, {('a', 1.0, 'needed', 20, 0)}),
    ([1, 0], 2, REIMPORT, set()),
    ([0, 1], 1, INCREMENTAL, {('a', 1.0, 'needed', 20, 1)}),
    ([0, 1], 2, INCREMENTAL, {('a', 1.0, 'needed', 20, 1)}),
    ([1, 0], 1, INCREMENTAL, {
        ('a', 0.0, 'needed', 20, 1),
        ('a', 1.0, 'needed', 20, 0),
    }),
    ([1, 0], 2, INCREMENTAL, {('a', 0.0, 'needed', 20, 1)}),
])
def test_correct_request_gets_marked_complete(
    state,
    request_list,
    reckoning_time,
    level,
    expected_result,
):
    """The correct request should get marked complete

    Regardless of reimport/incremental import and timing inputs, the correct
    request should get marked complete on a call to the mark_import_outcomes()
    method.

    :param target.State state: our pytest fixture that provides a target.State
        instance to test.
    :param list(int) request_list: for each monotonic pretend clock tick,
        whether a request at that time is for a reimport or an incremental
        import. 0 means incremental; 1 means reimport, as mapped to the
        database reimport column.
    :param reckoning_time: pass through to the call to mark_import_outcomes().
    :param Level level: pass through to the ImportRequest constructor for the
        single successful request that will be passed to
        mark_import_outcomes().
    :param set expected_result: the expected return value of the
        _dump_request() method.
    """
    for request in enumerate(request_list):
        inject_import_request(state, *request)
    state._normalize(state.db)

    state.mark_import_outcomes(reckoning_time, [ImportRequest('a', level)], [])
    assert state._dump_request() == expected_result


def test_failed_request_marked_correctly(state):
    """
    A failed request should get marked as errored

    :param target.State state: our pytest fixture that provides a target.State
        instance to test.
    """
    state.request_imports(['a', 'b'], request_time=1)
    state.mark_import_outcomes(2, [], [ImportRequest('a', INCREMENTAL)])
    assert state._dump_request() == set([
        ('a', 1.0, 'error', 20, 0),
        ('b', 1.0, 'needed', 20, 0),
    ])


def test_request_gets_marked_running(state):
    """
    A request marked as running should get updated in the database accordingly

    :param target.State state: our pytest fixture that provides a target.State
        instance to test.
    """
    state.request_imports(['a', 'b'], request_time=1)
    state.mark_running([ImportRequest('a', INCREMENTAL)])
    assert state._dump_request() == set([
        ('a', 1.0, 'running', 20, 0),
        ('b', 1.0, 'needed', 20, 0),
    ])


@pytest.mark.parametrize(['level'], [(INCREMENTAL,), (REIMPORT,)])
def test_correct_request_gets_marked_running(state, level):
    """
    The correct request should get marked running

    Regardless of incremental/reimport import inputs, the correct request
    should get marked running on a call to the mark_running() method.

    :param target.State state: our pytest fixture that provides a target.State
        instance to test.
    :param Level level: which of the two requests we are marking as running.
    """
    # Using this ordering, nothing gets superseded during normalization, so
    # this test can effectively check that the correct entry was marked running
    # because both entries will still exist in both cases.
    for request in enumerate([1, 0]):
        inject_import_request(state, *request)
    state._normalize(state.db)
    state.mark_running([ImportRequest('a', level)])
    assert state._dump_request() == set([
        ('a', float(not level.value), 'running', 20, level.value),
        ('a', float(level.value), 'needed', 20, int(not level.value)),
    ])


def test_normalize_superseding(state):
    state.request_imports(['a', 'b'], request_time=1)
    state.request_imports(['a'], request_time=2)
    assert state._dump_request() == set([
        ('a', 2.0, 'needed', 20, 0),
        ('b', 1.0, 'needed', 20, 0),
    ])
    state._normalize(state.db, assert_no_action=True)


def test_superseding_with_running(state):
    state.request_imports(['a'], request_time=1)
    state.mark_running([ImportRequest('a', INCREMENTAL)])
    state.request_imports(['a'], request_time=2)
    assert state._dump_request() == set([
        ('a', 2.0, 'needed', 20, 0),
        ('a', 1.0, 'running', 20, 0),
    ])


@pytest.mark.parametrize(['request_list', 'expected_result'], [
    (
        # incremental followed by incremental: first incremental gets
        # superseded
        [0, 0],
        [
            ('a', 0.0, 'superseded', 20, 0),
            ('a', 1.0, 'needed', 20, 0),
        ]
    ),
    (
        # reimport followed by reimport: first reimport gets superseded
        [1, 1],
        [
            ('a', 0.0, 'superseded', 20, 1),
            ('a', 1.0, 'needed', 20, 1),
        ]
    ),
    (
        # incremental followed by reimport: incremental gets superseded
        [0, 1],
        [
            ('a', 0.0, 'superseded', 20, 0),
            ('a', 1.0, 'needed', 20, 1),
        ]
    ),
    (
        # reimport followed by incremental: nothing gets superseded
        [1, 0],
        [
            ('a', 0.0, 'needed', 20, 1),
            ('a', 1.0, 'needed', 20, 0),
        ]
    ),
])
def test_superseding_with_reimports(state, request_list, expected_result):
    """Superseding should correctly collapse requests

    :param target.State state: our pytest fixture that provides a target.State
        instance to test.
    :param list(int) request_list: for each monotonic pretend clock tick,
        whether a request at that time is for a reimport or an incremental
        import. 0 means incremental; 1 means reimport, as mapped to the
        database reimport column.
    :param set expected_result: the expected return value of the
        _dump_request() method.
    """
    for request in enumerate(request_list):
        inject_import_request(state, *request)
    state._mark_superseded(state.db)
    assert state._dump_request() == set(expected_result)


def test_unmark_running(state):
    """unmark_running() should correctly update database state

    :param target.State state: our pytest fixture that provides a target.State
        instance to test.
    """
    state.request_imports(['a', 'b'], request_time=1)
    state.mark_running([ImportRequest('a', INCREMENTAL)])
    state.unmark_running()
    state._normalize(state.db, assert_no_action=True)
    assert state._dump_request() == set([
        ('a', 1.0, 'error', 20, 0),
        ('b', 1.0, 'needed', 20, 0),
    ])


def test_ensure_reimport_column_when_missing():
    """The reimport column should get added when not present"""
    db = sqlite3.connect(':memory:')
    db.cursor().execute('CREATE TABLE request (foo INTEGER NOT NULL)')
    target.State._ensure_reimport_column(db)
    cursor = db.cursor()
    cursor.execute('SELECT * FROM request')
    # The second column should have a name of 'reimport' now. See
    # https://www.python.org/dev/peps/pep-0249/#description
    assert cursor.description[1][0] == 'reimport'


def test_ensure_reimport_column_when_present():
    """The reimport column should not get added when already present"""
    db = sqlite3.connect(':memory:')
    db.cursor().execute('CREATE TABLE request (reimport INTEGER NOT NULL)')
    target.State._ensure_reimport_column(db)
    cursor = db.cursor()
    cursor.execute('SELECT * FROM request')
    # There should still only be one column
    # https://www.python.org/dev/peps/pep-0249/#description
    assert len(cursor.description) == 1


def test_empty_dump_ipc_worker(state):
    """_dump_ipc_worker() should return an empty set when the table is empty"""
    assert state._dump_ipc_worker() == set()


def test_assign_ipc_worker(state):
    """assign_ipc_worker() should update the request and ipc_worker tables

    :param target.State state: our pytest fixture that provides a target.State
        instance to test.
    """
    inject_import_request(state, 1, False)
    state.assign_ipc_worker('worker1', ImportRequest('a', INCREMENTAL), 1)
    assert state._dump_request() == {('a', 1.0, 'running', 20, 0)}
    assert state._dump_ipc_worker() == {('worker1', 'a', 0, 1)}


def test_lookup_ipc_worker(state):
    """lookup_ipc_worker() should return details of an assigned worker

    :param target.State state: our pytest fixture that provides a target.State
        instance to test.
    """
    inject_import_request(state, 1, False)
    state.assign_ipc_worker('worker1', ImportRequest('a', INCREMENTAL), 1)
    state.lookup_ipc_worker('worker1') == ('a', INCREMENTAL, 1)


def test_clear_ipc_worker(state):
    """clear_ipc_worker() should correctly update tables in the normal case

    :param target.State state: our pytest fixture that provides a target.State
        instance to test.
    """
    inject_import_request(state, 0, False)
    request = ImportRequest('a', INCREMENTAL)
    state.assign_ipc_worker('worker1', request, 1)
    state.mark_import_outcomes(1, [request], [])
    state.clear_ipc_worker('worker1')
    assert state._dump_request() == set()
    assert state._dump_ipc_worker() == set()


def test_clear_ipc_worker_when_not_assigned(state):
    """clear_ipc_worker() should do nothing if a worker isn't assigned

    :param target.State state: our pytest fixture that provides a target.State
        instance to test.
    """
    state.clear_ipc_worker('worker1')
    assert state._dump_ipc_worker() == set()


def test_clear_ipc_worker_that_never_finished(state):
    """clear_ipc_worker() should mark a request as errored if it isn't done

    :param target.State state: our pytest fixture that provides a target.State
        instance to test.
    """
    inject_import_request(state, 0, False)
    request = ImportRequest('a', INCREMENTAL)
    state.assign_ipc_worker('worker1', request, 1)
    state.clear_ipc_worker('worker1')
    assert state._dump_request() == {('a', 0.0, 'error', 20, 0)}
    assert state._dump_ipc_worker() == set()


def mock_call_request_new_imports(
    state,
    filter_func,
):
    """Helper to make a mock call to request_new_imports()

    request_new_imports() will be called a single mock publication in Ubuntu
    appearing at time 1 called test-package.

    :param target.State state: must be passed in by the caller: the "state"
        pytest fixture that provides a target.State instance to test.
    :param filter_func: parameter to pass through to the request_new_imports()
        call.
    :returns: None
    """
    lp = Mock(distributions={
        'debian': Mock(
            main_archive=Mock(getPublishedSources=Mock(return_value=[])),
        ),
        'ubuntu': Mock(main_archive=Mock(getPublishedSources=Mock(
            return_value=[
                Mock(
                    date_published=datetime.datetime.fromtimestamp(1),
                    source_package_name='test-package',
                ),
            ],
        ))),
    })
    state._write_timestamps({
        'debian': target.Timestamp(0, None),
        'ubuntu': target.Timestamp(0, None),
    })
    target.request_new_imports(
        lp=lp,
        num_days_ago=None,
        service_state=state,
        filter_func=filter_func,
        request_time=2.0,
    )


def test_request_new_imports_filter_func_true(state):
    """Package is requested when filter_func agrees

    :param target.State state: our pytest fixture that provides a target.State
        instance to test.
    """
    filter_func=Mock(return_value=False)
    mock_call_request_new_imports(state=state, filter_func=filter_func)
    filter_func.assert_called_once_with('test-package')
    assert state._dump_request() == frozenset()


def test_request_new_imports_filter_func_false(state):
    """Package is not requested when filter_func disagrees

    :param target.State state: our pytest fixture that provides a target.State
        instance to test.
    """
    filter_func=Mock(return_value=True)
    mock_call_request_new_imports(state=state, filter_func=filter_func)
    filter_func.assert_called_once_with('test-package')
    assert state._dump_request() == frozenset({
        ('test-package', 2.0, 'needed', 20, 0),
    })
