from .call_functions import get_or_create_nice_number
from .models import PhoneCall
from .rest import PhoneProviderRESTObject
from django.contrib.auth.decorators import permission_required
from django.contrib.auth.models import User
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from private import resources
from what_apps.contact.models import PhoneNumber, PhoneProvider
from what_apps.do.functions import get_tasks_in_prototype_related_to_object
from what_apps.utility.forms import get_bool_from_html
from what_apps.utility.models import FixedObject
import json
import logging
import os
import requests
import urlparse


comm_logger = logging.getLogger('comm')

def simple_phone_lookup(request):
    phone_number, created = get_or_create_nice_number(request.GET['phone_number'])
    if phone_number.owner:
        return HttpResponse(str(phone_number.owner))
    else:
        if created:
            return HttpResponse('unlogged new number')
        else:
            return HttpResponse('unlogged old number')


def outgoing_call_menu(request):
    outgoing_number = request.GET['phone_number']
    outgoing_number_object = PhoneNumber.objects.get(id=outgoing_number)
    
    member_role = FixedObject.objects.get(name="RoleInGroup__slashroot_holder").object
    eligible_members = member_role.users()
    
    eligible_numbers = []
    
    for member in eligible_members:
        for phone_number in member.userprofile.contact_info.phone_numbers.all():
            eligible_numbers.append([phone_number.id, phone_number.type, member.username, phone_number.number])
    
    #Hardcode the house line for now.
    eligible_numbers.append([687, 'house', 'SlashRoot', '845-418-5633'])
        
    return render(request, 'comm/outgoing_call_menu.html', locals()) 

def outgoing_call(request):
    '''
Make an outgoing call. Duh. :-)
TODO: Uncouple from Tropo
'''
    tropo_provider = PhoneProvider.objects.get(name="Tropo")
    
    call_from_phone = PhoneNumber.objects.get(id=request.POST['callFrom'])
    call_to_phone = PhoneNumber.objects.get(id=request.POST['callTo'])

    from_number = resources.SLASHROOT_MAIN_LINE
    
    
    response = requests.post('https://api.tropo.com/1.0/sessions/',
                      data={
                            'token':'0aaea1598824a846a340ea4b597fc9672cfa5734fc4a2edcf8c2de5101277f765ec7e8743d379495f7969bc7',
                            'toNumber':call_to_phone.remove_dashes(),
                            'fromNumber':call_from_phone.remove_dashes(),
                            }
                      )
    
    session_id = urlparse.parse_qs(response.content)['id'][0].rstrip()