#!/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 = 'fileek.com'
httpSiteUrl = 'http://' + siteUrl
addon = xbmcaddon.Addon(id='plugin.video.KinoPoisk.ru')
#__settings__ = xbmcaddon.Addon(id='plugin.video.KinoPoisk.ru')

__settings__ = xbmcaddon.Addon(id='plugin.video.KinoPoisk.ru')
#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 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://fileek.com', post=None):
	#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
		return ''

def GET2(target, referer='http://fileek.com'):
		import requests
		s = requests.session()
		r=s.get(url, verify=False).text
		#rd=r.encode('windows-1251')
		return r

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

def upd(info, p):
	text=info['title']
	#year1=str(info['year'])
	#year2=str(int(info['year'])+1)
	search=text.replace(' ','+')#urllib.quote(win())
	
	url= 'http://fileek.com/search/?q='+search+'&ft%5B%5D=cinema&page='+p
	url= 'http://fileek.com/search/?q='+search+'&fs%5B%5D=2&fs%5B%5D=3&fs%5B%5D=4&fs%5B%5D=5&ft%5B%5D=cinema&fc%5B%5D=&page='+p#+'&f_yf='+year1+'&f_yt='+year2+''
	print url
	http = GET(url)
	#debug (http)
	#print http
	if http == None:
		print 'Сервер не отвечает'
		return None
	else:
		return http

def Parser(http, info):
	Lout=[]
	print '====Parser====='
	title=info['title']
	
	
	hp=http[http.find('id="files_list"'):]
	ss='<div id="item_'
	es='>Загрузить<'
	Lid=[]
	L=mfindal(hp, ss,es)
	L2=[]
	for i in L:
		#if title in i and (year1 in i or year2 in i):
			#print i
			if 'download-btn' in i:
				id = mfind(i,'checkLink(',', &quot;')
				if id not in Lid:
					Lid.append(id)
					torrent=get_torrent(id)
					size=mfind(i, '<div class="size">', '</div>')
					title=mfind(i, 'href="#">', '</a></div>')
					seed='0'
					#print title
					#print torrent
					Lout.append({"sids":seed, "size":size, "title":xt(title),"url":torrent, "quality": ""})
					#print Lout
	return Lout

def get_torrent(id):
	print 'get_torrent '+id
	url = 'http://fileek.com/index.php?r=download/ajaxlinkcheck&id='+id+'&action=%2Fsearch&ismagnet=0'
	link=eval(GET(url).replace("\\/", "/"))['link']
	return link

def get_sz(url):
	http=GET(url)
	L=[25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1]
	for i in L:
		if 'season-'+str(i) in http: return i
	return 0

def Storr(info):
	Lout=[]
	#text=info['originaltitle']
	p = 1
	http=upd(info, str(p))
	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 Search(self, info):
		Lout=Storr(info)
		return Lout