# -*- coding: UTF-8 -*-
import hashlib
import os

from django.contrib import admin, messages
from app.models import ConsultationPlatform, Initiative, Campaign, SocialNetworkApp, Idea, Comment, Vote, \
                       SocialNetworkAppCommunity, SocialNetworkAppUser, ParticipaUser
from app.tasks import test_function
from app.error import AppError
from app.utils import call_social_network_api, calculate_token_expiration_time
from connectors.admin import do_request, get_json_or_error, get_url_cb, build_request_url
from connectors.error import ConnectorError


class SocialNetworkAdmin(admin.ModelAdmin):
    list_display = ('name', 'url', 'connector', )
    ordering = ('name', 'url', )
    actions = ['subscribe_real_time_updates', 'delete_subscription_real_time_updates']

    def delete_subscription_real_time_updates(self, request, queryset):
        for obj in queryset:
            if obj.subscribed_read_time_updates:
                connector = obj.connector
                post_data = {'object': obj.object_real_time_updates}
                try:
                    params = {'app': obj, 'data': post_data}
                    call_social_network_api(connector, 'delete_subscription_real_time_updates', params)
                    obj.subscribed_read_time_updates = False
                    obj.token_real_time_updates = None
                    obj.save()
                    self.message_user(request, 'Successful delete of the subscription to receive real time updates')
                except ConnectorError as e:
                    self.message_user(request, e.reason, level=messages.ERROR)
            else:
                self.message_user(request, 'The social network has not been subscribed to receive real time update',
                                  level=messages.WARNING)
    delete_subscription_real_time_updates.short_description = 'Delete subscription to receive real time updates'

    def subscribe_real_time_updates(self, request, queryset):
        try:
            for obj in queryset:
                if not obj.callback_real_time_updates or not obj.field_real_time_updates or \
                   not obj.object_real_time_updates or not obj.page_id:
                    self.message_user(request, 'Please indicate the page id, callback, field and object',
                                      level=messages.WARNING)
                else:
                    if not obj.subscribed_read_time_updates:
                        connector = obj.connector
                        token = hashlib.sha1(os.urandom(128)).hexdigest()
                        obj.token_real_time_updates = token
                        obj.save()
                        post_data = {'object': obj.object_real_time_updates,
                                     'fields': obj.field_real_time_updates,
                                     'callback_url': obj.callback_real_time_updates,
                                     'verify_token': token}
                        try:
                            params = {'app': obj, 'data': post_data}
                            call_social_network_api(connector, 'subscribe_real_time_updates', params)
                            obj.subscribed_read_time_updates = True
                            obj.save()
                            self.message_user(request, 'Successful subscription to receive real time updates')
                        except ConnectorError as e:
                            self.message_user(request, e.reason, level=messages.ERROR)
                    else:
                        self.message_user(request, 'Please delete the current subscription to receive real time '
                                                   'updates')
        except AppError as e:
            self.message_user(request, e.reason, level=messages.ERROR)
    subscribe_real_time_updates.short_description = 'Subscribe to receive real time updates'


class InitiativeAdmin(admin.ModelAdmin):
    list_display = ('name', 'url', 'consultation_platform', 'social_networks', 'hashtag', 'users', 'ideas', 'votes', 'comments', 'active', )
    ordering = ('name', 'url', 'hashtag', 'users', 'ideas', 'votes', 'comments', 'active', )