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

import httplib
import os
import Cookie

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


icon = ""
#siteUrl = 'hdpicture.ru'
#siteUrl = 'www.hdreactor.club'
siteUrl = 'hdreactor.in'
httpSiteUrl = 'http://' + siteUrl
addon = 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):
	x=x.decode('Windows-1251')
	x=x.encode('utf-8')
	return x

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


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://hdpicture.ru', post=None):
		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)')
		resp = urllib2.urlopen(req)
		http = resp.read()
		resp.close()
		print http
		return encod(http)


def win(s):return s.decode('utf-8').encode('windows-1251')


def Parser(hp, info):
	print 'parser'
	Lout=[]
	#hp=http[http.find('id="files_list"'):]
	ss='<div class="news-wrap">'
	es='<div class="bl"></div><div class="br">'
	Lid=[]
	L=mfindal(hp, ss,es)
	L2=[]
	for i in L:
		try:
					#print '---------------------'
					#title=mfind(i, '<h1>', '</h1>')
					#print title
					tmp=i[i.find('<!--QuoteEnd-->'):]
					uid = httpSiteUrl+mfind(tmp,'<a href="http://hdpicture.ru','.html')+'.html'
					#print uid
					tinfo=get_torrent(uid)
					print tinfo
					url=tinfo['torrent']
					if __settings__.getSetting("antizapret") == "true": url = azpt.convert(url)
					Lout.append({"sids":tinfo['seed'], "size":tinfo['size'], "title":tinfo['title'],"url":url, "quality": ""})
					#print Lout
		except:
					#print '=================================='
					#print i
					print ''
	return Lout

def get_torrent(url):
	hp=GET(url)
	#link='http://hdpicture.ru/engine/download.php?id='+mfind(hp, '/engine/download.php?id=', '">')
	link='magnet:'+mfind(hp, 'magnet:', '">')
	size=mfind(hp, '<b>Размер:</b> ', ' | ')
	seed=mfind(hp, 'li_distribute_m">', '</span>')
	title=mfind(hp, 'news-head h1"><h1>', '</h1>')
	return {'torrent':link, "title":title, 'size':size, 'seed':seed}

def Storr(info):
	Lout=[]
	text=info['originaltitle']
	post='do=search&titleonly=3&subaction=search&story='+urllib.quote_plus(coder(text))#&x=81&y=8'
	url=httpSiteUrl#+'/index.php?do=search'
	http=GET(url)#,'http://hdpicture.ru',post)
	print http
	Lout.extend(Parser(http, info))
	'''
	if 'href="#">2<' in http:
		p = 2
		http=upd(info, str(p))
		Lout.extend(Parser(http, info))
	if 'href="#">3<' in http:
		p = 3
		http=upd(info, str(p))
		Lout.extend(Parser(http, info))
	'''
	return Lout



class Tracker:
	def __init__(self):
		pass

	def Search(self, info):
		if __settings__.getSetting("Magnet")=='true':
			Lout=Storr(info)
			return Lout
		else:
			return []