# -*- coding: utf-8 -*-

from __future__ import division, print_function, unicode_literals

import json

from bson import json_util
from django.shortcuts import render
from django.views.generic import View
from django.conf import settings
from django.http import HttpResponse


def response(status, data):
    hr = HttpResponse()
    hr['Access-Control-Allow-Origin'] = '*'
    hr['Content-Type'] = 'application/json'
    hr['charset'] = 'utf-8'
    hr.status_code = status
    if type(data) == str or type(data) == unicode:
        data = {
            'message': data,
        }
    try:
        hr.write(json.dumps(data))
    except:
        try:
            hr.write(json.dumps(data, default=json_util.default))
        except:
            hr.status_code = 500
            hr.write(json.dumps({
                'error': "json serialize failed",
            }))
    return hr


def view(request, view_name, **kwargs):
    context = {
        'view': view_name,
        'site': settings.SITE,
    }
    context.update(kwargs)
    return render(request, 'view/{}.html'.format(view_name), context)


class Wrong(Exception):

    def __init__(self, status=500, data="Unknown error."):
        self.status = status
        self.data = data
        super(Wrong, self).__init__()


class HomeView(View):

    def get(self, request, *args, **kwargs):
        return view(request, 'home', gnb='home')


class WrongView(View):

    def get(self, request, *args, **kwargs):
        raise Wrong(400, "Just Wrong")


class WrongDataView(View):

    def get(self, request, *args, **kwargs):
        raise Wrong(400, {
            'message': "Just Wrong",
            'data': [],
        })
