#-*- coding: utf-8 -*-

import httplib
import json
from django.shortcuts import render_to_response, HttpResponse, redirect
from django.template import RequestContext
from oauth2app.models import Client, AccessToken
from django.contrib.auth.decorators import login_required
from django import forms
from apps.account.models import Profile
import settings

class LocationForm(forms.Form):
    location = forms.CharField()

#@login_required
def homepage(request):

    template = { "LOGIN_URL": settings.LOGIN_URL }

    if request.user.is_authenticated():
        user_profile = None
        try:
            user_profile = request.user.get_profile()
        except:
            # On first login, a user will not have a profile...what to do?
            new_profile = Profile()
            new_profile.user = request.user
        
            new_client = Client(name=request.user.username+"_pds", user=request.user, description="user "+request.user.username+"'s Personal Data Store", redirect_uri="http://"+new_profile.pds_location+"/?username="+request.user.username)
            new_client.save()
            new_profile.pds_client = new_client
            new_profile.save()
    
        if request.GET.get('location'):
            new_profile = request.user.get_profile()
            new_location = request.GET['location']
            new_profile.pds_location = new_location
            new_profile.save()
    
        clients = Client.objects.filter(user=request.user)
        access_tokens = AccessToken.objects.filter(user=request.user).select_related()
    #        access_tokens = access_tokens.select_related()
        form = LocationForm()
        #print access_tokens[0].token 
        template["access_token"] = access_tokens[0].token if len(access_tokens) > 0 else None
        template["clients"] = clients
        template["profile"] = user_profile
        template['form']=form
        template['isup']=is_pds_up(user_profile)
    
    return render_to_response(
        'base/homepage.html', 
        template, 
        RequestContext(request))


def is_pds_up(profile):
    '''Verifies that a user's PDS is set up and responding'''
#    pds_location = profile.pds_location
    try:
        path = str(profile.pds_location)#str(profile.pds_ip)+":"+str(profile.pds_port)
        print path
        conn = httplib.HTTPConnection(path, timeout=2.5)
        request_path="/discovery/ping"
        conn.request("GET",str(request_path))
        r1 = conn.getresponse()
        response_text = r1.read()
        print response_text
        result = json.loads(response_text)

        if result['success'] != True:
             raise Exception(result['message'])
        conn.close()
        return True
    except Exception as ex:
        print ex
        return False



    

#TODO DELETE this section. testing mongoEngine
# handle static pages (such as the About pg, Terms pg, and Privacy policy pg)
from mongoengine import *
class Puser(Document):
    email = StringField(required=True)
    first_name = StringField(max_length=50)
    last_name = StringField(max_length=50)
def static(request):

  connect('project1')#, username='webapp', password='pwd123')
  john = Puser(email='jdoe@example.com', first_name='sfds', last_name='S')
  john.save()
  str = ''
  for p in Puser.objects:
    str += p.first_name + ' ' +p.last_name + '<br/>'
  return HttpResponse(str)

def returnToAndroidApp(request):
    response = HttpResponse(content="", status=302)
    response["Location"] = "my_android_application:///dcapsdev.media.mit.edu/returnToAndroidApp"
    return response#HttpResponseRedirect('mypds-android-app:///dcapsdev.media.mit.edu/returnToAndroidApp')

@@ -28,27 +28,17 @@
 ort 
-httplib%0Aimport json
+requests%0A
 %0Afro
@@ -95,26 +95,16 @@
 Response
-, redirect
 %0Afrom dj
@@ -793,24 +793,16 @@
 st.user%0A
-        
 %0A       
@@ -1134,36 +1134,32 @@
 _profile.save()%0A
-    
 %0A        if requ
@@ -1370,20 +1370,16 @@
 .save()%0A
-    
 %0A       
@@ -1644,17 +1644,16 @@
 0%5D.token
- 
 %0A       
@@ -1899,20 +1899,16 @@
 rofile)%0A
-    
 %0A    ret
@@ -1960,17 +1960,16 @@
 e.html',
- 
 %0A       
@@ -1978,17 +1978,16 @@
 emplate,
- 
 %0A       
@@ -2022,427 +2022,329 @@
 def 
-is_pds_up(profile):%0A    '''Verifies that a user's PDS is set up and responding'''%0A#    pds_location = profile.pds_location%0A    try:%0A        path = str(profile.pds_location)#str(profile.pds_ip)+%22:%22+str(profile.pds_port)%0A        print path%0A        conn = httplib.HTTPConnection(path, timeout=2.5)%0A        request_path=%22/discovery/ping%22%0A        conn.request(%22GET%22,str(request_path))%0A        r1 = conn.getresponse()
+_read_json_success(response):%0A    %22%22%22Attempts to read the %60success%60 value from a JSON response, if%0A    applicable. Returns True or False%22%22%22%0A    if response.status_code != 200:%0A        return False%0A%0A    try:%0A        # requests %3E 1.0.0%0A        return response.json().get('success', False)%0A    except AttributeError:
 %0A       
  res
@@ -2343,283 +2343,391 @@
     
+ #
  re
-sponse_text = r1.read()%0A        print response_text%0A        result = json.loads(response_text)%0A%0A        if result%5B'success'%5D != True:%0A             raise Exception(result%5B'message'%5D)%0A        conn.close()%0A        return True%0A    except Exception as ex:%0A        print ex
+quests %3C 1.0.0 had a json attribute instead of a method.%0A        return response.json.get('success', False)%0A%0A%0Adef is_pds_up(profile, request_path=%22/discovery/ping%22, schema=%22http%22):%0A    '''Verifies that a user's PDS is set up and responding'''%0A    path = %22%7Bschema%7D://%7Bhost%7D%7Bpath%7D%22.format(%0A        schema=schema,%0A        host=profile.pds_location,%0A        path=request_path
 %0A    
+)%0A
     
@@ -2737,21 +2737,47 @@
 urn 
-False%0A%0A%0A%0A    
+_read_json_success(requests.get(path))%0A
 %0A%0A#T

replace httplib code with requests