import os
import shutil
import subprocess
import unittest

from werkzeug.test import Client
from werkzeug.wrappers import BaseResponse

app = """from testapp import settings
from testapp import views
from testapp.urls import url_map
from flast.app import BaseApp, create_app


class App(BaseApp):
    def __init__(self, settings):
        self.url_map = url_map
        self.views = views
        super(App, self).__init__(settings)

if __name__ == '__main__':
    from werkzeug.serving import run_simple
    app = create_app(App)
    run_simple('0.0.0.0', 5000, app, use_debugger=True, use_reloader=True)

app = create_app(App, settings,  with_static=settings.DEBUG)"""

views = """# create you views here. example:
# from flast.views import View
#
#
# class Index(View):
#     def get(self, request):
#         return self.render_template('index.html')"""

urls = """from werkzeug.routing import Map, Rule

url_map = Map([
         # Rule('/', endpoint='index'),
])"""


class TestFlastInit(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        subprocess.call(["flast-init.py", "testapp"])

    @classmethod
    def tearDownClass(cls):
        shutil.rmtree("testapp")

    def test_directories(self):
        for elem in os.listdir('testapp'):
            self.assertTrue(
                elem in ['statics', 'templates', 'sql', 'views.py', 'app.py',
                         '__init__.py', 'urls.py', 'settings.py'])

    def test_template_files(self):
        with open('testapp/app.py') as fd:
            self.assertEqual(app, fd.read())

        with open('testapp/views.py') as fd:
            self.assertEqual(views, fd.read())

        with open('testapp/urls.py') as fd:
            self.assertEqual(urls, fd.read())

    def test_views(self):
        from testapp.app import app
        c = Client(app, BaseResponse)
        resp = c.get('/')
        # no views/urls exists yet but service is running and responding
        self.assertEqual(resp.status_code, 404)

        from werkzeug.routing import Map, Rule
        url_map = Map([Rule('/', endpoint='index'), ])
        from flast.views import View

        class Index(View):
            def get(self, request):
                return self.render_template('index.html')

        class views(object):
            def __init__(self):
                self.Index = Index

        views = views()
        app.url_map = url_map
        app.views = views
        with open("testapp/templates/index.html", "w") as index:
            index.write("Hello World")

        c = Client(app, BaseResponse)
        resp = c.get('/')
        self.assertEqual(resp.status_code, 200)


if __name__ == '__main__' and __package__ is None:
    unittest.main()
