# Create your views here.

from django.shortcuts import render_to_response
from petra.rschecker.models import *

def links_checker_index(request):
	"""
		Shows the initial index for the rs link 
		checker
	"""
	return render_to_response("links_index.html")

def links_checker_check(request):
	"""
		Get urls to check from the textarea
		and check if those links are still
		valid.
	"""
	data = dict()

	links = get_link_list_from_request(request)
	validated_links = check_links(links)

	if validated_links[0] == 0 or len(validated_links[1]) <> len(links):
		data["error"] = 1
	else:
		data["links"] = list()
		for i in range(len(links)):
			item = dict()
			item["url"] = links[i]
			item["valid"] = validated_links[1][i]
			data["links"].append(item)
	
	return render_to_response("links_index.html", data) 	

def links_checker_fetch(request):
	"""
		Get all rapidshare links from a url
	"""
	data = dict()
	if not request.POST.has_key("url"):
		data["error"] = 1
	else:
		#Get url from post params
		url = request.POST["url"]

		#Get a list of UNIQUE links
		links = list(set(scan_links_from_url(url)))
		#Get validation status
		validated_links = check_links(links)

		#Check for errors
		if validated_links[0] == 0 or len(validated_links[1]) <> len(links):
			data["error"] = 1
		else:
			#Build info items to use in the template
			data["links"] = list()
			for i in range(len(links)):
				item = dict()
				item["url"] = links[i]
				item["valid"] = validated_links[1][i]
				data["links"].append(item)

	return render_to_response("links_index.html", data)
