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

import urllib, urllib2, time
import os
import cookielib

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


icon = ""
siteUrl = 'videolenta.biz'
httpSiteUrl = 'https://' + siteUrl
#addon = xbmcaddon.Addon(id='plugin.video.KinoPoisk.ru')
sid_file = os.path.join(xbmc.translatePath('special://temp/'), 'lenta.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=httpSiteUrl, post=None):
		req = urllib2.Request(url = target, data = post)
		req.add_header('User-Agent', 'Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Mobile Safari/537.36')#'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 Parser2(url):
	#print '====2==='
	#print url
	hp = GET(url)
	Lout=[]
	L = mfindal(hp,'<span class="ttip"', 'document_save.png></a>')
	#print len(L)
	#if len(L) == 0: print hp
	title = encod(mfind(hp, 'notop"><span itemprop="name">', '</td>')).replace('</span><br>',' ').strip()#.replace('торрент','')
	print title
	year = mfind(hp, 'id="t_year" class="rightrow norightborder">', '</td>').strip()
	for i in L:
		print '====i===='
		print i
		try:
					url =httpSiteUrl+'/downloadt'+mfind(i, '"/downloadt', '"')
					print url
					qual = mfind(i,'>','<')
					print qual
					size = mfind(mfind(i, '<td data-sort-value=', 'td>'),'">','<').strip()
					if 'МБ' in size: size = size[:size.find('.')]+'MB'
					elif len(size)-size.find('.')>4: 
						size = size[:size.find('.')+3]+'GB'
					print size
					sids = '?'
					
					
					if '<br><i>' in i:sound = encod(mfind(i,'<br><i>','<'))
					else: sound =''
					if len(sound)>100 or '/>' in sound: sound =''
					
					if '<td>' in i: sez = encod(mfind(i,'<td>','<'))
					else: sez =''
					if len(sez)>30 or '/>' in sez: sez =''
					print sez
					#if __settings__.getSetting("antizapret") == "true": url = azpt.convert(url)
					Lout.append({"sids":sids, "size":size, "title":title+" "+year+" "+sez+" ["+qual+"] "+sound, "url":url, "quality": qual})
					#print Lout
		except:
					#print '=================================='
					print i
					print 'err'
	#print Lout
	return Lout

def Parser1(hp, info):
	LL=[]
	L = hp.splitlines()
	for i in L:
		if 'class="c_title"' in i :#and info['title'] in i
			url = httpSiteUrl+mfind(i,'<a href="','"')
			LL.append(url)
			#print url
	return LL

def Parser(hp, info):
	L=[]
	L1=Parser1(hp, info)
	for url in L1:
		L2 = Parser2(url)
		#return L2
		L.extend(L2)
	return L

def Storr(info):
	text=info['originaltitle']
	#print text
	url=httpSiteUrl+'/torrentz/search/'+urllib.quote_plus(text).replace('+','%20')+'/'
	print url
	http=GET(url,httpSiteUrl)
	#print http
	Lout=Parser(http, info)
	if Lout==[]: 
		text=info['title']
		url=httpSiteUrl+'/torrentz/search/'+urllib.quote_plus(text).replace('+','%20')+'/'
		http=GET(url,httpSiteUrl)
		Lout=Parser(http, info)
	return Lout



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

#Storr('info')
