# Copyright 2020 The StackStorm Authors.
# Copyright 2019 Extreme Networks, Inc.
#
# 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.

from __future__ import absolute_import
import mock
import json
import logging
import unittest2

from tests import base

from st2client import models
from st2client.utils import httpclient


LOG = logging.getLogger(__name__)


class TestSerialization(unittest2.TestCase):
    def test_resource_serialize(self):
        instance = base.FakeResource(id="123", name="abc")
        self.assertDictEqual(instance.serialize(), base.RESOURCES[0])

    def test_resource_deserialize(self):
        instance = base.FakeResource.deserialize(base.RESOURCES[0])
        self.assertEqual(instance.id, "123")
        self.assertEqual(instance.name, "abc")


class TestResourceManager(unittest2.TestCase):
    @mock.patch.object(
        httpclient.HTTPClient,
        "get",
        mock.MagicMock(
            return_value=base.FakeResponse(json.dumps(base.RESOURCES), 200, "OK")
        ),
    )
    def test_resource_get_all(self):
        mgr = models.ResourceManager(base.FakeResource, base.FAKE_ENDPOINT)
        resources = mgr.get_all()
        actual = [resource.serialize() for resource in resources]
        expected = json.loads(json.dumps(base.RESOURCES))
        self.assertListEqual(actual, expected)

    @mock.patch.object(
        httpclient.HTTPClient,
        "get",
        mock.MagicMock(
            return_value=base.FakeResponse(json.dumps(base.RESOURCES), 200, "OK")
        ),
    )
    def test_resource_get_all_with_limit(self):
        mgr = models.ResourceManager(base.FakeResource, base.FAKE_ENDPOINT)
        resources = mgr.get_all(limit=50)
        actual = [resource.serialize() for resource in resources]
        expected = json.loads(json.dumps(base.RESOURCES))
        self.assertListEqual(actual, expected)

    @mock.patch.object(
        httpclient.HTTPClient,
        "get",
        mock.MagicMock(
            return_value=base.FakeResponse("", 500, "INTERNAL SERVER ERROR")
        ),
    )
    def test_resource_get_all_failed(self):
        mgr = models.ResourceManager(base.FakeResource, base.FAKE_ENDPOINT)
        self.assertRaises(Exception, mgr.get_all)

    @mock.patch.object(
        httpclient.HTTPClient,
        "get",
        mock.MagicMock(
            return_value=base.FakeResponse(json.dumps(base.RESOURCES[0]), 200, "OK")
        ),
    )
    def test_resource_get_by_id(self):