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

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

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


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

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')
		#req.add_header('Content-Type', 'application/x-www-form-urlencoded')
		#req.add_header('Referer', referer)
		#req.add_header('Origin', referer)
		#req.add_header('Content-Type', 'application/x-www-form-urlencoded')
		#req.add_header('Content-Type', 'application/x-www-form-urlencoded')
		
		resp = urllib2.urlopen(req)
		http = resp.read()
		resp.close()
		return http#encod()

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=[]
	L = mfindal(hp,'<out_', '</out_')
	for i in L:
		try:
				if len(mfind(i, '<sizeb>', '</sizeb>')) > 8:
					url ='https://krasfs.ru/download.php?hash='+mfind(i, '<hash>', '</hash>')
					#print url
					title = mfind(i, '<name>', '</name>')
					alt_name = mfind(i, 'alt_name', '</alt_name>')
					#print title
					size = mfind(i, '<sizef>', '</sizef>')
					if 'Мб' in size: size = size[:size.find('.')]+'MB'
					elif len(size)-size.find('.')>4: 
						size = size[:size.find('.')+3]+'GB'
					sids = '?'
					Lout.append({"sids":sids, "size":size, "title":title, "url":url, "quality": alt_name})
					#print Lout
		except:
					#print '=================================='
					#print i
					print 'err'
	return Lout


def Storr(info):
	Lout=[]
	text=info['originaltitle']#coder()
	#text=coder('terminator')
	try:    key = __settings__.getSetting("krasfs_key")
	except: key = ''
	
	if key == '':
		key=mfind(GET('https://krasfs.ru/search?key=newkey'), '<newkey>', '</newkey>')
		__settings__.setSetting("krasfs_key", key)
	print key
	url='https://krasfs.ru/search?key='+key+'&depth=1360&query='+urllib.quote_plus(text)+'&out=xml&type=torrent'#+urllib.quote_plus(text)
	print url
	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')