# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json

from django.http import JsonResponse
from django.contrib.auth.decorators import login_required

from app.friends import get_friends_light_states, get_friend_by_fb_id
from app.lights import Lights

@login_required
def json_friends_light_states(request):
    friends_light_states = get_friends_light_states(request.user)
    return JsonResponse({
        'status': 'success',
        'data': friends_light_states
    })

@login_required
def ping_light(request):
    lucem_user_friends = request.user.lucemuser.friends

    lucem_user_friends_ids = [k['id'] for k in lucem_user_friends]
    target_fb_id = request.POST['target_fb_id']

    # Verify that target_fb_id is in lucem_user_friends
    if target_fb_id not in lucem_user_friends_ids:
        return JsonResponse({
            'status': 'error',
            'data': 'You are not authorized to ping this user.'
        }, status=401)

    # Perform ping
    friend_profile = get_friend_by_fb_id(target_fb_id)
    friend_lifx_token = friend_profile.lifx_token

    lights = Lights(friend_lifx_token)
    lights.ping_user_lights()

    return JsonResponse({
        'status': 'success',
        'data': 'Ping sent.'
    })
