# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import sys
from events.surveyme.models import (
    Survey,
    SurveyQuestion,
    SurveyQuestionShowConditionNode,
    SurveySubmitConditionNode,
    SurveyText,
)
from events.surveyme.api_admin.v2.serializers import (
    SurveyDetailSerializer,
    SurveyQuestionSerializer,
    SurveyQuestionShowConditionNodeSerializer,
    SurveySubmitConditionNodeSerializer,
    SurveyTextSerializer,
)
from events.followme.api_admin.v2.serializers import (
    ContentFollowerSerializer,
)
from rest_framework.renderers import JSONRenderer


def export_survey_to_dict(survey_id):
    survey = Survey.objects.get(pk=survey_id)
    extra = {
        'context': {
            'request': None,
        },
    }
    json_renderer = JSONRenderer()

    survey_serializer = SurveyDetailSerializer(survey, **extra)
    survey_bytes = json_renderer.render(survey_serializer.data)

    questions = SurveyQuestion.objects.filter(survey=survey_id)
    questions_serializer = SurveyQuestionSerializer(questions, many=True, **extra)
    questions_bytes = json_renderer.render(questions_serializer.data)

    questions_show_conditions = SurveyQuestionShowConditionNode.objects.filter(survey_question__survey=survey_id)
    questions_show_conditions_serializer = SurveyQuestionShowConditionNodeSerializer(questions_show_conditions, many=True, **extra)
    questions_show_conditions_bytes = json_renderer.render(questions_show_conditions_serializer.data)

    nodes = SurveySubmitConditionNode.objects.filter(survey=survey_id)
    nodes_serializer = SurveySubmitConditionNodeSerializer(nodes, many=True, **extra)
    nodes_bytes = json_renderer.render(nodes_serializer.data)

    texts = SurveyText.objects.filter(survey=survey_id)
    texts_serializer = SurveyTextSerializer(texts, many=True, **extra)
    texts_bytes = json_renderer.render(texts_serializer.data)

    followers_serializer = ContentFollowerSerializer(survey.followers, many=True, **extra)
    followers_bytes = json_renderer.render(followers_serializer.data)

    return {
        'survey': json.loads(survey_bytes.decode()),
        'questions': json.loads(questions_bytes.decode()),
        'questions_show_conditions': json.loads(questions_show_conditions_bytes.decode()),
        'nodes': json.loads(nodes_bytes.decode()),
        'texts': json.loads(texts_bytes.decode()),
        'followers': json.loads(followers_bytes.decode()),
    }


def main():
    if len(sys.argv) != 2:
        return
    survey_id = sys.argv[1]
    survey_dict = export_survey_to_dict(survey_id)
    with open('survey_%s.json' % survey_id, 'w') as f:
        survey_json = json.dumps(survey_dict, indent=2, ensure_ascii=False)
        print(survey_json)
        print(survey_json, file=f)


if __name__ == '__main__':
    main()
