# coding=utf-8

import traceback
import json

from django.views.decorators.csrf import csrf_exempt
from django.db import transaction,IntegrityError
from django.db.models import ProtectedError

from apps.foundation.filters import OptionFilter
from libs.http import JSONResponse, JSONError, DataGridJSONResponse
from libs import utils
from apps.exceptions import CustomError
from apps.account.decorators import token_required,permission_required

from models import Option
from serializers import OptionSerializer
from resources import OptionResource
from apps.dashboard.forms import fetch_license
from django.core.cache import cache

@csrf_exempt
@permission_required('foundation.view_option')
def option_list(request):
    f = OptionFilter(request.GET, queryset=Option.objects.all())
    rows, total = utils.get_page_data(request, f.qs)
    serializer = OptionSerializer(rows, many=True)

    return DataGridJSONResponse(serializer.data, total)

@csrf_exempt
@permission_required('foundation.add_option')
def option_save(request):
    id = request.GET.get('id')
    data = json.loads(request.body)
    try:
        with transaction.atomic():
            serializer = OptionSerializer.factory(request.user,data,id)
            serializer.validSave()
    except CustomError, e:
        return JSONError(e.get_error_msg())
    except Exception, e:
        traceback.print_exc()
        return JSONError(u'保存失败！')
    return JSONResponse()

@permission_required('foundation.delete_option')
def option_delete(request):
    id = request.GET.get('id')

    try:
        with transaction.atomic():
            option = Option.getById(id)
            option.delete()
    except CustomError, e:
        return JSONError(e.get_error_msg())
    except ProtectedError:
        return JSONError(u'该自定义项已被使用，禁止删除！')
    except IntegrityError:
        return JSONError(u'该自定义项已被使用，禁止删除！')
    except Exception, e:
        traceback.print_exc()
        return JSONError(u'删除失败！')
    return JSONResponse({})

@csrf_exempt
@token_required
def option_types(request):
    data = []
    for row in Option.TYPE_CHOICES:
        data.append(
            {'id': row[0], 'value': row[1]}
        )

    return JSONResponse(data)

@csrf_exempt
@token_required
def log_list(request):
    pass

def mobile_license(request):
    try:
        fetch_license()
    except Exception, e:
        return JSONError(e.message)

    license = cache.get('license')
    result = {
        'allow_app':license['allow_app'],
    }
    return JSONResponse(result)

@csrf_exempt
@token_required
def search_options(request):
    type = int(request.GET.get('type'))
    rows = Option.objects.filter(type=type, enabled=True)
    data = []
    for row in rows:
        item = {
            'id': row.id,
            'name': row.name
        }
        data.append(item)

    return JSONResponse(data)