import json
from django.contrib.auth import get_user_model

from django.core.urlresolvers import reverse
from django.db.utils import IntegrityError
from django.shortcuts import HttpResponse, render
from django.shortcuts import render_to_response

from elgassia.settings import DEBUG
from main.models import MainMenu, StandardPage, Config
from main.utils.decorators import staff_member_required


@staff_member_required()
def main_menu_save(request):
    error = ''

    try:
        menu_db = MainMenu.objects
        idx = request.POST.getlist('idx[]')
        title = request.POST.getlist('title[]')
        dest_page = request.POST.getlist('dest_page[]')
        dest_url = request.POST.getlist('dest_url[]')
        remove = request.POST.getlist('remove[]')

        for pos, entry in enumerate(zip(idx, remove, title, dest_page, dest_url)):
            if entry[0] == '-1':
                if entry[1] == 'true':
                    continue
                k = MainMenu()
            else:
                k = menu_db.get(id=entry[0])
                if entry[1] == 'true':
                    k.delete()
                    continue
            k.position = pos

            if entry[3] == 'new':
                dest_page = StandardPage()
                dest_page.title = entry[2]
                dest_page.save()
                entry = list(entry)
                entry[3] = dest_page.id

            k.title, k.dest_page, k.dest_url = entry[2:]
            k.save()
    except Exception as e:
        if DEBUG:
            error += str(e)
        else:
            error += 'Saving Error'

    response = {'success': error == '', 'error': error}
    return HttpResponse(json.dumps(response), content_type='application/json')


@staff_member_required()
def page_list(request):
    return render(request, 'main/config/page_list.html', {
        'pages': StandardPage.objects.all()
    })


@staff_member_required()
def page_list_save(request):