from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
from django.shortcuts import render
from django.utils.html import escape
from django.views.decorators.csrf import csrf_exempt

import functions

#import os
#import sys
#path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'crawler/'))
#if not path in sys.path:
#    sys.path.insert(1, path)
#del path 
#from crawler import web_crawl

def index(request):
	return render(request, 'index.html')

def display_page(request):
	if 'uname' in request.GET and request.GET['uname']:
		username = request.GET['uname']
		try:
			if username=='root':
				return render(request, 'report.html', {'user_name': username})
			else:
				return render(request, username+'.html', {'user_name': username})
		except:
			response = """
									Either the username is invalid or this user doens't	
									have any page with broken links
									"""
			return HttpResponse(response)
	return HttpResponse('Empty')

def mock_page(request):
	if ('url' in request.GET and request.GET['url'] and 'uname' in request.GET and 
		request.GET['uname']) and ('location' in request.GET and request.GET['location']):
		fname = request.GET['url']
		uname = request.GET['uname']
		location = request.GET['location']
		print 'fname : ' + fname
		
		#if condition below makes sure that url doesn't end with '/'
		# And while loop below gets the file name of the mock page for the given url
		#		E.g. if the URL is http://www3.imperial.ac.uk/computing the file name will
		#		be computing
		if fname.endswith("/"):
			fname = fname[:-1]
		while fname.find('/') != -1:
			fname = fname[fname.find('/')+1:]
		try:
			return render(request, location + '/' + fname + '.html')
		except:
			response = """The feature you asked for is not working for this page.\n 
							Please contact doc-wmproject2013_u@imperial.ac.uk.\n
							We will try fix it as soon as possible.					
					"""
			return HttpResponse(response)
	return HttpResponse('Empty')


@csrf_exempt #TODO try doing it without excluding csrf
def see_source(request):
	if request.method == 'POST':
		try:
			url = request.POST['url']
			pointer_to_anchor = request.POST['pointers']
			code = functions.get_code_to_display(url, pointer_to_anchor)
			return HttpResponse(code)
		except:
			response = """ The feature you asked for is not working for this page.\n 
							Please contact doc-wmproject2013_u@imperial.ac.uk.\n
							We will try fix it as soon as possible."""
			return HttpResponse(response);
	return HttpResponse('No source code to display!')
