from __future__ import print_function, unicode_literals, with_statement, division

from os import path, system, listdir, sys, mkdir
from django.conf import settings
# VIEW CONSTS

LIST_VIEW = """
from %(app)s.forms import %(model)sForm
def %(lower_model)s_list(request, template='%(lower_model)s/list.html'):
    d = {}
    d['form'] = %(model)sForm()
    if request.method == 'POST':
        form = %(model)sForm(request.POST)
        if form.is_valid():
            item = form.save()
            return JsonResponse(data={'id': item.id, 'name': str(item), 'form': %(model)sForm().as_p(), 'token': get_token(request)})
        else:
            d['form'] = form
            return JsonResponse(data={'form': d['form'].as_p(), 'token': get_token(request)}, success=False)
    d['%(lower_model)s_list'] = %(model)s.objects.all()
    return render(request, template, d)
"""

DETAILS_VIEW = """
from %(app)s.forms import %(model)sForm
def %(lower_model)s_details(request, id, template='%(lower_model)s/details.html'):
    d = {}
    item = get_object_or_404(%(model)s, pk=id)
    d['form'] = %(model)sForm(instance=item)
    if request.method == 'POST':
        form = %(model)sForm(request.POST, instance=item)
        if form.is_valid():
            item = form.save()
            return JsonResponse(data={'form': %(model)sForm(instance=item).as_p(), 'token': get_token(request)})
        else:
            d['form'] = form
            return JsonResponse(data={'form': d['form'].as_p(), 'token': get_token(request)}, success=False)
    d['%(lower_model)s'] = %(model)s.objects.get(pk=id)
    return render(request, template, d)
"""

DELETE_VIEW = """
def %(lower_model)s_delete(request, id):
    item = %(model)s.objects.get(pk=id)
    item.delete()
    return JsonResponse()
"""
# MODELS CONSTS

MODEL_TEMPLATE = """
class %s(models.Model):
    %s
    update_date = models.DateTimeField(auto_now=True)
    create_date = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-id']
"""

IMPORT_MODEL_TEMPLATE = """from %(app)s.models import %(model)s"""

CHARFIELD_TEMPLATE = """
    %(name)s = models.CharField(max_length=%(length)s, null=%(null)s, blank=%(null)s)
"""

TEXTFIELD_TEMPLATE = """
    %(name)s = models.TextField(null=%(null)s, blank=%(null)s)
"""

INTEGERFIELD_TEMPLATE = """
    %(name)s = models.IntegerField(null=%(null)s, default=%(default)s)
"""

DECIMALFIELD_TEMPLATE = """
    %(name)s = models.DecimalField(max_digits=%(digits)s, decimal_places=%(places)s, null=%(null)s, default=%(default)s)
"""

DATETIMEFIELD_TEMPLATE = """
    %(name)s = models.DateTimeField(null=%(null)s, default=%(default)s)
"""

FOREIGNFIELD_TEMPLATE = """
    %(name)s = models.ForeignKey(%(foreign)s, null=%(null)s, blank=%(null)s)
"""

TEMPLATE_LIST_CONTENT = """
{%% extends "base.html" %%}

{%% block page-title %%}%(title)s{%% endblock %%}

{%% block content %%}
    <h1>%(model)s list</h1><br />
    <table style="border: solid 1px gray; width: 300px; text-align: center;" id="item-list">
        <tr style="background-color: #DDD">
            <th style="padding: 10px;">ID</th>
            <th>Name</th>
            <th>Action</th>
        </tr>
    {%% for item in %(model)s_list %%}
        <tr>
            <td style="padding: 10px;">{{ item.id }}</td>
            <td>{{ item }}</td>
            <td><a href="{%% url '%(model)s-details' item.id %%}">show</a></td>
        </tr>
    {%% endfor %%}
    </table>
    <br />
    <input type="button" onclick="$('#add-form-div').toggle();" value="Add new %(model)s"><br /><br />
    <div id="add-form-div" style="display: none;">
        <form action="{%% url '%(model)s-list' %%}" method="POST" id="add-form">
                <div id="form-fields">
                    {%% csrf_token %%}
                    {{ form }}
                </div>
                <input type="submit" value="Submit" />
        </form>
    </div>

    <script type="text/javascript">
        (new FormHelper('add-form')).bind_for_ajax(
            function(data) {
                $('#item-list').append('<td style="padding: 10px;">' + data.id + '</td><td>' + data.name + '</td><td><a href="{%% url %(model)s-list %%}' + data.id + '/">show</a></td>').hide().fadeIn();
                $('#form-fields').html('');
                $('#form-fields').append('<input type="hidden" value="' + data.token + '" name="csrfmiddlewaretoken">');
                $('#form-fields').append(data.form);
                $('#add-form-div').toggle();
            },
            function(data) {
                $('#form-fields').html('');
                $('#form-fields').append('<input type="hidden" value="' + data.token + '" name="csrfmiddlewaretoken">');
                $('#form-fields').append(data.form).hide().fadeIn();
                $('#add-form input[type=submit]').removeAttr('disabled');
            }
        );
    </script>
{%% endblock %%}
"""

TEMPLATE_DETAILS_CONTENT = """
{%% extends "base.html" %%}

{%% block page-title %%}%(title)s - {{ %(model)s }} {%% endblock %%}

{%% block content %%}
    <div class="item">
        <h1>%(model)s - {{ %(model)s }} </h1><br />
        <table style="border: solid 1px gray; width: 300px; text-align: center;" id="item-list">
            <tr style="background-color: #DDD">
                <th style="padding: 10px;">ID</th>
                <th>Name</th>
                <th>Action</th>
            </tr>
            <tr>
                <td style="padding: 10px;">{{ %(model)s.id }}</td>
                <td>{{ %(model)s }}</td>
                <td><input type="button" href="{%% url '%(model)s-delete' %(model)s.id %%}" id="delete-item" value="delete" /></td>
            </tr>
        </table>
        <br />
        <br />
        <br />
        <input type="button" onclick="$('#add-form-div').toggle();" value="Edit %(model)s"><br /><br />
        <div id="add-form-div" style="display: none;">
            <form action="{%% url '%(model)s-details' %(model)s.id %%}" method="POST" id="add-form">
                    <div id="form-fields">
                        {%% csrf_token %%}
                        {{ form }}
                    </div>
                    <input type="submit" value="Submit" />
            </form>
        </div>
    </div>

    <script type="text/javascript">
        (new FormHelper('add-form')).bind_for_ajax(
            function(data) {
                $('#form-fields').html('');
                $('#form-fields').append('<input type="hidden" value="' + data.token + '" name="csrfmiddlewaretoken">');
                $('#form-fields').append(data.form).hide().fadeIn();
                $('#add-form input[type=submit]').removeAttr('disabled');
            },
            function(data) {
                $('#form-fields').html('');
                $('#form-fields').append('<input type="hidden" value="' + data.token + '" name="csrfmiddlewaretoken">');
                $('#form-fields').append(data.form).hide().fadeIn();
                $('#add-form input[type=submit]').removeAttr('disabled');
            }
        );
        $('#delete-item').click(function() {
            $.get($(this).attr('href'), function(data) {
                $('div.item').before('<h1>Item removed</h1><br /><br />');
                $('div.item').remove();
            });
        });
    </script>
    <a href="{%% url '%(model)s-list' %%}">back to list</a>
{%% endblock %%}
"""

URL_CONTENT = """
from django.conf.urls import url
from django.contrib.auth import views as auth_views

from %(app)s import views

urlpatterns = [
    url(r'^%(model)s/$', views.%(model)s_list, name='%(model)s-list'),
    url(r'^%(model)s/(?P<id>\d+)/$', views.%(model)s_details, name='%(model)s-details'),
    url(r'^%(model)s/(?P<id>\d+)/delete/$', views.%(model)s_delete, name='%(model)s-delete'),
]
"""

URL_EXISTS_CONTENT = """
    url(r'^%(model)s/$', views.%(model)s_list, name='%(model)s-list'),
    url(r'^%(model)s/(?P<id>\d+)/$', views.%(model)s_details, name='%(model)s-details'),
    url(r'^%(model)s/(?P<id>\d+)/delete/$', views.%(model)s_delete, name='%(model)s-delete'),
"""

ADMIN_CONTENT = """
from %(app)s.models import %(model)s
admin.site.register(%(model)s)
"""

FORM_CONTENT = """

from %(app)s.models import %(model)s

class %(model)sForm(forms.ModelForm):
    class Meta:
        model = %(model)s
"""

TESTS_CONTENT = """

from %(app)s.models import %(model)s


class %(model)sTest(TestCase):

    def setUp(self):
        self.user = User.objects.create(username='test_user')

    def tearDown(self):
        self.user.delete()

    def test_list(self):
        response = self.client.get(reverse('%(lower_model)s-list'))
        self.failUnlessEqual(response.status_code, 200)

    def test_crud(self):
        # Create new instance
        response = self.client.post(reverse('%(lower_model)s-list'), {})
        self.assertContains(response, '"success": true')

        # Read instance
        items = %(model)s.objects.all()
        self.failUnlessEqual(items.count(), 1)
        item = items[0]
        response = self.client.get(reverse('%(lower_model)s-details', kwargs={'id': item.id}))
        self.failUnlessEqual(response.status_code, 200)

        # Update instance
        response = self.client.post(reverse('%(lower_model)s-details', kwargs={'id': item.id}), {})
        self.assertContains(response, '"success": true')

        # Delete instance
        response = self.client.post(reverse('%(lower_model)s-delete', kwargs={'id': item.id}), {})
        self.assertContains(response, '"success": true')
        items = %(model)s.objects.all()
        self.failUnlessEqual(items.count(), 0)

"""


class Scaffold(object):
    def _info(self, msg, indent=0):
        print("{0} {1}".format("\t" * int(indent), msg))

    def __init__(self, app, model, fields):
        self.app = app
        self.model = model
        self.fields = fields

        try:
            self.SCAFFOLD_APPS_DIR = settings.SCAFFOLD_APPS_DIR
        except:
            self.SCAFFOLD_APPS_DIR = './'