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

import urllib, urllib2, time
import os
import cookielib

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


icon = ""
siteUrl = 'bitru.org'
httpSiteUrl = 'http://' + siteUrl
#addon = xbmcaddon.Addon(id='plugin.video.KinoPoisk.ru')
sid_file = os.path.join(xbmc.translatePath('special://temp/'), 'bitru.cookies.sid')
cj = cookielib.FileCookieJar(sid_file)
hr  = urllib2.HTTPCookieProcessor(cj)

__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='http://torrent.by', post=None):
		req = urllib2.Request(url = target, data = post)
		req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 OPR/50.0.2762.67')
		resp = urllib2.urlopen(req)
		http = resp.read()
		resp.close()
		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'
	#print hp
	#hp.replace('Размер</td></tr>','')
	Lout=[]
	L = mfindal(hp,'<div style="position:relative;">', '<td align="center" title="Качают">')
	for i in L:
		#print i
		try:
				#if len(mfind(i, '<sizeb>', '</sizeb>')) > 8:
					url =httpSiteUrl+'/download.php?id='+mfind(i, 'details.php?id=', '"')
					print url
					title = mfind(i, 'onmouseout="UnTip()">', '<').strip()
					print title
					size = mfind(i, 'title="Размер">', '<').strip()
					if 'МБ' in size: size = size[:size.find('.')]+'MB'
					elif len(size)-size.find('.')>4: 
						size = size[:size.find('.')+3]+'GB'
					print size
					if 'b-seeders">' in i: sids = mfind(i, 'b-seeders">', '<').strip()
					else: sids = '0'
					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):
	text=info['originaltitle']
	url=httpSiteUrl+'/browse.php?s='+urllib.quote_plus(text.replace(' ','+'))+'&sort=seeders'
	http=GET(url,httpSiteUrl)
	Lout=Parser(http)
	if Lout==[]: 
		text=info['title']
		url=httpSiteUrl+'/browse.php?s='+urllib.quote_plus(text.replace(' ','+'))+'&sort=seeders'
		http=GET(url,httpSiteUrl)
		Lout=Parser(http)
	return Lout



class Tracker:
	def __init__(self):
		pass

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

#Storr('info')
