# mysite/api/graphene_wagtail.py
# Taken from https://github.com/patrick91/wagtail-ql/blob/master/backend/graphene_utils/converter.py and slightly adjusted
import logging

from graphene.types import Scalar
from graphene_django.converter import convert_django_field
from graphql_relay import to_global_id
from wagtail.core.fields import StreamField
from wagtail.images.models import Image

from assignments.models import Assignment
from basicknowledge.models import BasicKnowledge
from surveys.models import Survey

logger = logging.getLogger(__name__)


class GenericStreamFieldType(Scalar):
    @staticmethod
    def serialize(stream_value):
        stream_data = stream_value.stream_data
        return augment_fields(stream_data)

        # by_api = stream_value.stream_block.get_api_representation(stream_value)
        # return by_api


def augment_fields(stream_data):
    for data in stream_data:
        if isinstance(data, dict):
            _type = data['type']
            if _type == 'image_block':
                _value = data['value']
                value = {
                    # 'value': _value,
                    # 'id': d['id'],
                    'path': Image.objects.get(id=_value).file.url
                }
                data['value'] = value
            if _type == 'assignment':
                _value = data['value']
                assignment_id = _value['assignment_id']
                try:
                    assignment = Assignment.objects.get(pk=assignment_id)
                    value = {
                        'title': assignment.title,
                        'assignment': assignment.assignment,
                        'id': to_global_id('AssignmentNode', assignment.pk)
                    }
                    data['value'] = value
                except Assignment.DoesNotExist:
                    logger.error('Assignment {} does not exist'.format(assignment_id))
            if _type == 'survey':
                _value = data['value']
                survey_id = _value['survey_id']
                try:
                    survey = Survey.objects.get(pk=survey_id)
                    value = {
                        'title': survey.title,
                        'id': to_global_id('SurveyNode', survey.pk)
                    }
                    data['value'] = value
                except Survey.DoesNotExist:
                    logger.error('Survey {} does not exist'.format(survey_id))
            if _type == 'basic_knowledge' or _type == 'instrument':
                _value = data['value']
                basic_knowledge = BasicKnowledge.objects.get(pk=_value['basic_knowledge'])
                _value.update({
                    'slug': basic_knowledge.slug
                })
                data['value'] = _value

                # value = dict(d['value'])
                # if 'document' in value:
                #     value['document'] = Document.objects.get(id=value['document']).file.url
                # if 'image' in value:
                #     value['image'] = Image.objects.get(id=value['image']).file.url

                # else:
                #     _type = d[0]
                #     value = dict(d[1])
                #     if 'document' in value:
                #         value['document'] = value['document'].file.url
                #     if 'image' in value:
                #         value['image'] = value['image'].file.url

            if _type == 'content_list_item':
                item_data = data['value']
                data['value'] = augment_fields(item_data)

    return stream_data


@convert_django_field.register(StreamField)
def convert_stream_field(field, registry=None):
    return GenericStreamFieldType(description=field.help_text, required=not field.null)

