# Copyright (C) 2020, 2021 The Meme Factory, Inc.  http://www.karlpinc.com/

# This file is part of PGWUI_Common.
#
# This program is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public License
# as published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License along with this program.  If not, see
# <http://www.gnu.org/licenses/>.
#

# Karl O. Pinc <kop@karlpinc.com>

import pytest

from pgwui_develop import testing
from pgwui_common import plugin


# Helper classes
class MockEntryPoint():
    def __init__(self, val):
        self.__module__ = val
        self.__name__ = val

    def resolve(self):
        return self


class MockPkgResources():
    def __init__(self, entry_points):
        self.entry_points = entry_points

    def iter_entry_points(self, *args):
        return [MockEntryPoint(name) for name in self.entry_points]


# get_component()

@pytest.mark.unittest
def test_get_component():
    '''Returns the expected value
    '''
    result = plugin.get_component('package.module')
    assert result == 'package'


mock_get_component = testing.make_mock_fixture(
    plugin, 'get_component')


# find_pgwui_components()

@pytest.mark.unittest
def test_find_pgwui_components(mock_get_component, monkeypatch):
    '''Returns list of entry points via iter_entry_points()
    '''
    entry_points = ['a', 'b', 'c']

    mock_get_component.side_effect = lambda x: x
    monkeypatch.setattr(
        plugin, 'pkg_resources', MockPkgResources(entry_points))

    result = plugin.find_pgwui_components()

    assert result == entry_points


# find_pgwui_check_settings
@pytest.mark.unittest
def test_find_pgwui_check_settings(mock_get_component, monkeypatch):
    '''Returns a dict, keyed by name, of entry points
    '''
    entry_points = ['a', 'b', 'c']

    mock_get_component.side_effect = lambda x: x
    monkeypatch.setattr(
        plugin, 'pkg_resources', MockPkgResources(entry_points))

    result = plugin.find_pgwui_check_settings()

    assert isinstance(result, dict)
    assert list(result.keys()).sort() == entry_points.sort()
