#!/bin/sh

set -e

run() {
  echo "Running “$@”"
  $@
}

run django-admin startproject testproject
cd testproject
# python3 manage.py startapp tutorial
run python3 manage.py startapp tutorial

# Create necessary configuration
sed "s/INSTALLED_APPS = \[/INSTALLED_APPS = [\n    'django_tables2',\n    'tutorial',/" -i testproject/settings.py
sed "s/ALLOWED_HOSTS = \[/ALLOWED_HOSTS = ['testserver'/" -i testproject/settings.py

cat > tutorial/models.py << __EOF__
from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=100, verbose_name='full name')
__EOF__

run python3 manage.py makemigrations tutorial
run python3 manage.py migrate tutorial

run python3 manage.py shell << __EOF__
from tutorial.models import Person
Person.objects.bulk_create([Person(name='Jieter'), Person(name='Bradley')])
__EOF__

cat > tutorial/views.py << __EOF__
from django.shortcuts import render
from django_tables2 import RequestConfig
from .models import Person
from .tables import PersonTable

def people(request):
    table = PersonTable(Person.objects.all())
    RequestConfig(request).configure(table)
    return render(request, 'tutorial/people.html', {'table': table})
__EOF__


cat > testproject/urls.py << __EOF__
from django.urls import re_path
from django.contrib import admin

from tutorial.views import people

urlpatterns = [
    re_path(r'^admin/', admin.site.urls),
    re_path(r'^people/', people)
]
__EOF__

mkdir -p tutorial/templates/tutorial
cat > tutorial/templates/tutorial/people.html << __EOF__
{% load render_table from django_tables2 %}
<!doctype html>
<html>
    <head>
        <title>List of persons</title>
        <link rel="stylesheet" href="file:///usr/share/javascript/bootstrap/css/bootstrap.min.css" />
    </head>
    <body>
        {% render_table table %}
    </body>
</html>
__EOF__



cat > tutorial/tables.py << __EOF__
import django_tables2 as tables
from .models import Person

class PersonTable(tables.Table):
    class Meta:
        model = Person
        template_name = 'django_tables2/bootstrap.html'
__EOF__

cat > verify.py << __EOF__
from django.test import Client
client = Client()
response = client.get('/people/')
assert response.status_code == 200, "Response code is not 200"
body = response.content.decode('utf-8')
assert 'Jieter' in body, "The string 'Jieter' should be in the response"
assert 'Bradley' in body, "The string 'Bradley' should be in the response"
__EOF__

run python3 manage.py shell < verify.py

cd ..
rm -rf testproject
