import unittest

from base64 import b64encode
from klon_core.data import HubDatabase
from klon_hub.run import test_app
from flask_testing import TestCase

access_pw = "some password i dunno"
db = HubDatabase._create_in_memory(access_pw=access_pw)


class FrontendTest(TestCase):
    def create_app(self):
        db.clear()
        return test_app(db)

    def open_with_auth(self, url):
        user_and_pw = b64encode(":{}".format(access_pw).encode()).decode("ascii")
        auth_header = 'Authorization', 'Basic {}'.format(user_and_pw)
        return self.app.test_client().get(url, headers={auth_header})

    def test_index_redirect_to_nodes(self):
        r = self.open_with_auth("/")
        self.assertRedirects(r, "/nodes")

    def test_nodes_template(self):
        r = self.open_with_auth("/nodes")
        self.assert200(r)
        self.assert_template_used('nodes.html')

    def test_nodes_context_empty(self):
        r = self.open_with_auth("/nodes")
        self.assert200(r)
        self.assertEqual(self.get_context_variable('nodes'), [])

    def test_songs_template(self):
        r = self.open_with_auth("/songs")
        self.assert200(r)
        self.assert_template_used('songs.html')

    def test_songs_context_empty(self):
        r = self.open_with_auth("/songs")
        self.assert200(r)
        self.assertEqual(self.get_context_variable('songs'), [])

    def test_history_template(self):
        r = self.open_with_auth("/history")
        self.assert200(r)
        self.assert_template_used('history.html')

    def test_history_context_empty(self):
        r = self.open_with_auth("/history")
        self.assert200(r)
        self.assertEqual(self.get_context_variable('history'), [])


if __name__ == '__main__':
    unittest.main()
