#!/usr/bin/python
# -*- coding: utf-8 -*-

import urllib, urllib2, time
#import os
#import Cookie

import string, xbmc, xbmcgui, xbmcplugin, cookielib, xbmcaddon
#-------------------------------


icon = ""
siteUrl = 'www.picktorrent.com'
httpSiteUrl = 'http://' + siteUrl
#addon = xbmcaddon.Addon(id='plugin.video.KinoPoisk.ru')
#__settings__ = xbmcaddon.Addon(id='plugin.video.KinoPoisk.ru')


__settings__ = xbmcaddon.Addon(id='plugin.video.KinoPoisk.ru')
if __settings__.getSetting("antizapret") == "true":
	try:
		import azpt
		opener = azpt.get_opener()
		urllib2.install_opener(opener)
		print 'antizapret ok'
	except:
		print 'except set proxy'

def ru(x):return unicode(x,'utf8', 'ignore')
def xt(x):return xbmc.translatePath(x)

def encod(x):
	try:x=x.decode('Windows-1251')
	except:pass
	try:x=x.encode('utf-8')
	except:pass
	return x


def coder(x):
	x=x.decode('utf-8')
	x=x.encode('Windows-1251')
	return x

def lower(t):
	RUS={"А":"а", "Б":"б", "В":"в", "Г":"г", "Д":"д", "Е":"е", "Ё":"ё", "Ж":"ж", "З":"з", "И":"и", "Й":"й", "К":"к", "Л":"л", "М":"м", "Н":"н", "О":"о", "П":"п", "Р":"р", "С":"с", "Т":"т", "У":"у", "Ф":"ф", "Х":"х", "Ц":"ц", "Ч":"ч", "Ш":"ш", "Щ":"щ", "Ъ":"ъ", "Ы":"ы", "Ь":"ь", "Э":"э", "Ю":"ю", "Я":"я"}
	for i in range (65,90):
		t=t.replace(chr(i),chr(i+32))
	for i in RUS.keys():
		t=t.replace(i,RUS[i])
	return t


def mfindal(http, ss, es):
	L=[]
	while http.find(es)>0:
		s=http.find(ss)
		e=http.find(es)
		i=http[s:e]
		L.append(i)
		http=http[e+2:]
	return L

def mfind(t,s,e):
	r=t[t.find(s)+len(s):]
	r2=r[:r.find(e)]
	return r2


def debug(s):
	fl = open(ru(os.path.join( addon.getAddonInfo('path'),"test.txt")), "wb")
	fl.write(s)
	fl.close()


def GET(target, referer='https://www.picktorrent.com', post=None):
		if __settings__.getSetting("antizapret") == "true": target=azpt.convert(target)
		print target
		req = urllib2.Request(url = target, data = post)
		req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C)')
		req.add_header('Content-Type', 'text/plain;charset=UTF-8')
		resp = urllib2.urlopen(req)
		http = resp.read()
		resp.close()
		if __settings__.getSetting("antizapret") == "true": http=azpt.decoder(http)
		#print http
		return http

def clear(s):
	L=['<b>','</b>','</a>','</td>']
	for i in L:
		s=s.replace(i,'')
	s=s.replace(chr(10),'').replace(chr(13),'').replace('\t','').strip()
	return s

def Parser(hp):
	print 'parser'
	Lout=[]
	#hp=http[http.find('id="files_list"'):]
	if __settings__.getSetting("antizapret") == "true": ss='<a href="'
	else: ss='<a href="/download/'
	es='</tr>'
	Lid=[]
	hp=hp[hp.find('<tr class="zebra"'):]
	L=mfindal(hp, ss,es)
	L2=[]
	for i in L:
		try:
					#print '---------------------'
					#print i
					#i=encod(i)
					t1=i[:i.find('</td>')]
					t2=i[i.find('</td>')+5:].replace(chr(10),'').replace(chr(13),'').replace('<td >','<td>').replace('\t','').replace('  ','')
					#if __settings__.getSetting("antizapret") == "true":  url= mfind(t1, '<a href="', '">')
					#else: 
					url='https://www.picktorrent.com/t_'+mfind(t1, '/download/', '.html')+'.php'
					#print url
					title=clear(t1[t1.find('<b>'):])
					#print title
					L3=mfindal(t2,'<td>','</td>')
					sids = L3[2][4:].strip()
					size = L3[1][4:].replace('\t','').replace('  ','').strip()
					#print sids
					#print size
					if 'zee18' not in url:
						if __settings__.getSetting("antizapret") == "true": url = azpt.convert(url)
						Lout.append({"sids":sids, "size":size, "title":title, "url":url, "quality": ""})
					#print Lout
		except:
					#print '=================================='
					#print i
					print 'err'
	return Lout


def Storr(info):
	Lout=[]
	#text='матрица'
	text=lower(info['title'])#original.replace(' ', '-')
	#url='https://www.picktorrent.com/torrents/%D1%82%D0%B8%D1%82%D0%B0%D0%BD%D0%B8%D0%BA/'
	url='https://www.picktorrent.com/torrents/'+urllib.quote_plus(text)+'/'
	#print url
	http=GET(url,'https://www.picktorrent.com')
	Lout=Parser(http)
	#http=GET(url,url, 'text='+urllib.quotе_plus(text)+'&page=2')
	#L2=Parser(http)
	#Lout.extend(L2)
	return Lout



class Tracker:
	def __init__(self):
		pass

	def Search(self, info):
		Lout=Storr(info)
		return Lout

#Storr('info')