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

import os
import Cookie
import string, xbmc, xbmcgui, xbmcplugin, urllib, cookielib, xbmcaddon
#-------------------------------
import urllib, urllib2, time, random

#import HTMLParser 
#hpar = HTMLParser.HTMLParser()
#-----------------------------------------
import socket
socket.setdefaulttimeout(50)

icon = ""
siteUrl = 'freebfg.org'
httpSiteUrl = 'http://' + siteUrl

sid_file = os.path.join(xbmc.translatePath('special://temp/'), 'freebfg.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'
	#	opener = urllib2.build_opener(hr) 
	#	urllib2.install_opener(opener)
'''
def unlock(url):
	url='http://127.0.0.1:8095/proxy/'+url
	return url

def ru(x):return unicode(x,'utf8', 'ignore')
def xt(x):return xbmc.translatePath(x)
def fs(s):return s.decode('windows-1251').encode('utf-8')

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 rulower(str):
	str=str.strip()
	str=xt(str).lower()
	str=str.replace('Й','й')
	str=str.replace('Ц','ц')
	str=str.replace('У','у')
	str=str.replace('К','к')
	str=str.replace('Е','е')
	str=str.replace('Н','н')
	str=str.replace('Г','г')
	str=str.replace('Ш','ш')
	str=str.replace('Щ','щ')
	str=str.replace('З','з')
	str=str.replace('Х','х')
	str=str.replace('Ъ','ъ')
	str=str.replace('Ф','ф')
	str=str.replace('Ы','ы')
	str=str.replace('В','в')
	str=str.replace('А','а')
	str=str.replace('П','п')
	str=str.replace('Р','р')
	str=str.replace('О','о')
	str=str.replace('Л','л')
	str=str.replace('Д','д')
	str=str.replace('Ж','ж')
	str=str.replace('Э','э')
	str=str.replace('Я','я')
	str=str.replace('Ч','ч')
	str=str.replace('С','с')
	str=str.replace('М','м')
	str=str.replace('И','и')
	str=str.replace('Т','т')
	str=str.replace('Ь','ь')
	str=str.replace('Б','б')
	str=str.replace('Ю','ю')
	return str


def GET(target, referer='', post=None):
	if __settings__.getSetting("antizapret") == "true": target = unlock(target)
	#print target
	try:
		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)')
		resp = urllib2.urlopen(req)
		http = resp.read()
		resp.close()
		return http
	except Exception, e:
		print e


def Storr(text):
	surl='http://www.freebfg.org/browse.php?tmp=serial&search='+urllib.quote(text)
	http=http = GET(surl, httpSiteUrl, None)
	ss='<tr style="font-size: 8pt; ">'
	es='</b></b></a></td>'
	L=mfindal(http, ss, es)
	Lout=[]
	k=0
	TLD=[]
	defekt=0
	for j in L:
			L2=j.splitlines()
			url = ''
			title = ''
			size = '0'
			sids = '0'
			for i in L2:
				if 'style="border-right: 0px' in i: 
													url = 'http://www.freebfg.org/download.php?id='+i[i.find('id=')+3:i.find('"><b>')]
													title = i[i.find('"><b>')+5:i.find('</b></a>')].replace('<acronym title="','').replace('</acronym>','').replace('&nbsp;','')
				if 'white-space' in i:				size = i[i.find('">')+2:i.find('</td')]
				if 'toseeders' in i:				sids = i[i.find('0">')+3:i.find('</font></a')]
			if title != '': 
				if __settings__.getSetting("antizapret") == "true": url = unlock(url)
				Lout.append({"sids":sids, "size":size, "title":fs(title), "url":url})
	return Lout


class Tracker:
	def Search(self, info):
		text=info['originaltitle']
		Lout=Storr(text)
		return Lout