import json
import logging

from django.contrib import admin
from django.contrib.postgres.fields import JSONField
from django.forms import widgets
from django.utils.html import format_html
from graphql_relay import to_global_id

from api.utils import get_object

logger = logging.getLogger(__name__)

# Register your models here.
from surveys.models import Survey, Answer


class PrettyJSONWidget(widgets.Textarea):

    def format_value(self, value):
        try:
            value = json.dumps(json.loads(value), indent=2, sort_keys=True)
            # these lines will try to adjust size of TextArea to fit to content
            row_lengths = [len(r) for r in value.split('\n')]
            self.attrs['rows'] = min(max(len(row_lengths) + 2, 10), 30)
            self.attrs['cols'] = min(max(max(row_lengths) + 2, 40), 120)
            return value
        except Exception as e:
            logger.warning("Error while formatting JSON: {}".format(e))
            return super(PrettyJSONWidget, self).format_value(value)


class JSONAdmin(admin.ModelAdmin):
    formfield_overrides = {
        JSONField: {'widget': PrettyJSONWidget}
    }

@admin.register(Survey)
class SurveyAdmin(JSONAdmin):
    list_display = ('title', 'link',)

    def link(self, obj):
        return format_html('<a href="/survey/{id}" target="_blank">Link</a>', id=to_global_id('SurveyNode', obj.pk))
    link.short_description = 'Link'

@admin.register(Answer)
class AnswerAdmin(JSONAdmin):
    pass
