# -*- coding: utf-8 -*-
from requests.exceptions import HTTPError
from django.utils.translation import ugettext_lazy as _

from events.common_app.kinopoisk import KinopoiskAPIClient
from events.surveyme_integration.variables.base import BaseVariableCategory, BaseVariable, BaseRenderer


class KinopoiskVariableCategory(BaseVariableCategory):
    name = 'kinopoisk'
    title = _('Кинопоиск')
    order = 12


class KinopoiskProfileTxtRenderer(BaseRenderer):
    format_name = 'txt'
    format_title = _('Простой текст')

    def render(self, data):
        return '\n'.join(['%s: %s' % (i['title'], i['value']) for i in data])


class KinopoiskBaseVariable(BaseVariable):
    category = KinopoiskVariableCategory()
    what_to_get = None

    def get_value(self, format_name=None):
        if not self.answer.user.is_anonymous:
            try:
                profile_data = KinopoiskAPIClient().get_user_profile_data(uid=self.answer.user.uid)
            except HTTPError as e:
                if e.code == 404:
                    return '[NOT FOUND]'
                else:
                    raise
            else:
                return profile_data.get(self.what_to_get)


class KinopoiskEmailVariable(KinopoiskBaseVariable):
    name = 'kinopoisk.email'
    title = _('Email')
    what_to_get = 'email'


class KinopoiskIsBetaUserVariable(KinopoiskBaseVariable):
    name = 'kinopoisk.is_beta_user'
    title = _('Пользователь beta-версии')
    what_to_get = 'betaUser'


class KinopoiskUserIdVariable(KinopoiskBaseVariable):
    name = 'kinopoisk.userid'
    title = _('Id пользователя')
    what_to_get = 'userId'


class KinopoiskMigrationStatusVariable(KinopoiskBaseVariable):
    name = 'kinopoisk.migration_status'
    title = _('Статус миграции')
    what_to_get = 'migrationStatus'
