# All Rights Reserved 2018
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import operator
from unittest import mock

from openstack.network.v2 import network as sdk_network
from osc_lib import utils as osc_utils
from osc_lib.utils import columns as column_util

from neutronclient.tests.unit.osc.v2 import fakes as test_fakes

from networking_l2gw.l2gatewayclient.osc import l2gw_connection as \
    osc_l2gw_conn
from networking_l2gw.l2gatewayclient.osc import sdk_objects
from networking_l2gw.tests.unit.l2gatewayclient.osc import fakes


columns_long = tuple(col for col, _, listing_mode in osc_l2gw_conn._attr_map
                     if listing_mode in (column_util.LIST_BOTH,
                                         column_util.LIST_LONG_ONLY))
headers_long = tuple(head for _, head, listing_mode in osc_l2gw_conn._attr_map
                     if listing_mode in (column_util.LIST_BOTH,
                                         column_util.LIST_LONG_ONLY))
sorted_attr_map = sorted(osc_l2gw_conn._attr_map, key=operator.itemgetter(1))
sorted_columns = tuple(col for col, _, _ in sorted_attr_map)
sorted_headers = tuple(head for _, head, _ in sorted_attr_map)
columns = (
    'id',
    'l2_gateway_id',
    'network_id',
    'segmentation_id',
)


def _get_data(attrs, columns=sorted_columns):
    return osc_utils.get_dict_properties(attrs, columns)


def _get_columns(item):
    column_map = {}
    hidden_columns = ['location', 'tenant_id']
    return osc_utils.get_osc_show_columns_for_sdk_resource(
        item,
        column_map,
        hidden_columns
    )


class TestCreateL2gwConnection(test_fakes.TestNeutronClientOSCV2):
    def setUp(self):
        super().setUp()
        self.cmd = osc_l2gw_conn.CreateL2gwConnection(
            self.app, self.namespace)

    def test_create_l2gateway_connection(self):
        """Test Create l2gateway-connection."""

        fake_connection = fakes.FakeL2GWConnection.create_l2gw_connection()

        self.app.client_manager.network = mock.Mock()
        self.app.client_manager.network._create = mock.Mock(
            return_value=fake_connection)
        self.app.client_manager.network._find = mock.Mock(
            return_value=sdk_objects.L2gw(
                **{'id': fake_connection['l2_gateway_id']}))
        self.app.client_manager.network.find_network = mock.Mock(
            return_value=sdk_network.Network(
                **{'id': fake_connection['network_id']}))

        arg_list = [
            fake_connection['l2_gateway_id'],
            fake_connection['network_id'],
            '--default-segmentation-id', fake_connection['segmentation_id']
        ]
        verify_list = [
            ('gateway_name', fake_connection['l2_gateway_id']),
            ('network', fake_connection['network_id']),
            ('seg_id', fake_connection['segmentation_id'])
        ]

        parsed_args = self.check_parser(self.cmd, arg_list, verify_list)
        columns, data = self.cmd.take_action(parsed_args)
        self.app.client_manager.network._create.assert_called_once_with(
            sdk_objects.L2gwConnection,
            **{'segmentation_id': fake_connection['segmentation_id'],
               'network_id': fake_connection['network_id'],
               'l2_gateway_id': fake_connection['l2_gateway_id']}
        )
        self.assertEqual(columns, columns)
        fake_data = _get_data(
            fake_connection,
            _get_columns(fake_connection)[1])
        self.assertEqual(fake_data, data)
        self.assertItemEqual(fake_data, data)


class TestListL2gwConnection(test_fakes.TestNeutronClientOSCV2):
    def setUp(self):
        super().setUp()
        self.cmd = osc_l2gw_conn.ListL2gwConnection(self.app, self.namespace)

    def test_list_l2gateway_connection(self):
        """Test List l2gateway-connections."""

        fake_connections = fakes.FakeL2GWConnection.create_l2gw_connections(
            count=3)

        self.app.client_manager.network = mock.Mock()
        self.app.client_manager.network._list = mock.Mock(
            return_value=fake_connections)
        arg_list = []
        verify_list = []

        parsed_args = self.check_parser(self.cmd, arg_list, verify_list)

        headers, data = self.cmd.take_action(parsed_args)

        self.app.client_manager.network._list.assert_called_once()
        self.assertEqual(headers, list(headers_long))
        self.assertListItemEqual(
            list(data),
            [_get_data(fake_connection, columns_long) for fake_connection
             in fake_connections]
        )


class TestShowL2gwConnection(test_fakes.TestNeutronClientOSCV2):
    def setUp(self):
        super().setUp()
        self.cmd = osc_l2gw_conn.ShowL2gwConnection(self.app, self.namespace)
        self.app.client_manager.network._find = mock.Mock(
            side_effect=lambda _, name_or_id: {'id': name_or_id})

    def test_show_l2gateway_connection(self):
        """Test Show l2gateway-connection."""

        fake_connection = fakes.FakeL2GWConnection.create_l2gw_connection()

        self.app.client_manager.network._get = mock.Mock(
            return_value=fake_connection)
        arg_list = [fake_connection['id']]
        verify_list = [
            (osc_l2gw_conn.L2_GATEWAY_CONNECTION, fake_connection['id'])
        ]

        parsed_args = self.check_parser(self.cmd, arg_list, verify_list)

        headers, data = self.cmd.take_action(parsed_args)

        self.app.client_manager.network._get.assert_called_once_with(
            sdk_objects.L2gwConnection, {'id': fake_connection['id']})
        self.assertEqual(columns, headers)
        fake_data = _get_data(
            fake_connection,
            _get_columns(fake_connection)[1])
        self.assertEqual(fake_data, data)


class TestDeleteL2gwConnection(test_fakes.TestNeutronClientOSCV2):
    def setUp(self):
        super().setUp()
        self.app.client_manager.network = mock.Mock()
        self.app.client_manager.network._find = mock.Mock(
            side_effect=lambda _,
            name_or_id: sdk_objects.L2gw(**{'id': name_or_id}))
        self.cmd = osc_l2gw_conn.DeleteL2gwConnection(self.app, self.namespace)

    def test_delete_l2gateway_connection(self):
        """Test Delete l2gateway-connection."""

        fake_connection = fakes.FakeL2GWConnection.create_l2gw_connection()
        self.app.client_manager.network._delete = mock.Mock()
        arg_list = [fake_connection['id']]
        verify_list = [
            (osc_l2gw_conn.L2_GATEWAY_CONNECTIONS, [fake_connection['id']])
        ]

        parsed_args = self.check_parser(self.cmd, arg_list, verify_list)

        result = self.cmd.take_action(parsed_args)

        self.app.client_manager.network._delete.assert_called_once_with(
            sdk_objects.L2gwConnection, fake_connection['id'])
        self.assertIsNone(result)
