# -*- coding: utf-8 -*-
import sys, os
import urllib, urllib2

temp_dir = "c:\\"

genres={
	"Пародия":"25",
	"По игре":"26",
	"Повседневность":"27",
	"Меха":"21",
	"Музыка":"23",
	"Постапокалиптика":"29",
	"Этти":"2",
	"Мистика":"4",
	"Фантастика":"6",
	"Гарем":"98",
	"Детектив":"11",
	"Драма":"13",
	"Дзёсэй":"12",
	"Киберпанк":"15",
	"Исторический":"14",
	"Криминал":"17",
	"Медицина":"19",
	"Махо-сёдзё":"18",
	"Сёдзё-ай":"51",
	"Лайв-экшн":"50",
	"Сверхъестественное":"53",
	"Экшен":"52",
	"Дорамы":"48",
	"История":"49",
	"Подкасты":"47",
	"Фэнтези":"42",
	"Вампиры":"43",
	"Трэш":"40",
	"Ужасы":"41",
	"Комедия":"1",
	"Школа":"3",
	"Приключения":"5",
	"Боевые искусства":"7",
	"Война":"9",
	"Триллер":"39",
	"Сэйнэн":"38",
	"Сёдзе":"33",
	"Самурайский боевик":"32",
	"Романтика":"31",
	"Психология":"30",
	"Спорт":"37",
	"Сёнэн-ай":"35",
	"Сёнэн":"34",
	}

years={
	"[B]90-е[/B]":"199",
	"[B]80-е[/B]":"198",
	"[B]2000-е[/B]":"200",
	"[B]2010-е[/B]":"201",
	"2000":"2000",
	"2001":"2001",
	"2002":"2002",
	"2003":"2003",
	"2004":"2004",
	"2005":"2005",
	"2006":"2006",
	"2007":"2007",
	"2008":"2008",
	"2009":"2009",
	"2010":"2010",
	"2011":"2011",
	"2012":"2012",
	"2013":"2013",
	"2014":"2014",
	"2015":"2015",
	"2016":"2016",
	"2017":"2017",
	}

type={
	"ТВ-сериал":"%D0%A2%D0%92",
	"Фильмы":"%D0%9F%D0%BE%D0%BB%D0%BD%D0%BE%D0%BC%D0%B5%D1%82%D1%80%D0%B0%D0%B6%D0%BD%D1%8B%D0%B9",
	"OVA, ONA, Special":"OVA",
	"Дорама":"%D0%94%D0%BE%D1%80%D0%B0%D0%BC%D0%B0",
	}

ongoing={
	"Сейчас выходит":"n",
	"Вышедшие":"y",
	}

def ru(x):return unicode(x,'utf8', 'ignore')

def CRC32(buf):
		import binascii
		buf = (binascii.crc32(buf) & 0xFFFFFFFF)
		return str("%08X" % buf)

def unlock(url):
	try:
		import xbmcaddon
		__settings__ = xbmcaddon.Addon(id='plugin.video.animedia.tv')
		if __settings__.getSetting("ProxyON")=='true': Proxy = True
		else: Proxy = False
	except:
		Proxy = True
	if Proxy:
		url='http://127.0.0.1:8095/proxy/'+url
	return url

def GET(url, Referer = 'https://animedia.tv/'):
	url = unlock(url)
	req = urllib2.Request(url)
	req.add_header('User-Agent', 'Opera/10.60 (X11; openSUSE 11.3/Linux i686; U; ru) Presto/2.6.30 Version/10.60')
	req.add_header('Accept', 'text/html, application/xml, application/xhtml+xml, */*')
	req.add_header('Accept-Language', 'ru,en;q=0.9')
	req.add_header('Referer', Referer)
	response = urllib2.urlopen(req)
	link=response.read()
	response.close()
	return link


def findall(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 save_inf(s):
	p = os.path.join(ru(temp_dir),"temp.txt")
	f = open(p, "w")
	f.write(s)
	f.close()
	return p

def get_list(t='',g='',y='',o='',s='entry_date'):
	if o!='':o='&search:ongoing='+o
	if t!='':t='&search:type='+t
	if y!='':y='&search:datetime='+y
	if g!='':g='&category='+g
	url='https://tt.animedia.tv/ajax/search_result/P0?limit=100'+o+g+y+t+'&orderby_sort='+s+'|desc'
	print url
	r=GET(url)
	L=findall(r,'<div class="card__item">','<i class="ai ai-next">')
	L2=[]
	for i in L:
		id     = mfind(i,'/anime/','">')
		title  = mfind(i,'Постер аниме ','">')
		rating = mfind(i,'raitings">','/')
		cover  = 'https:'+mfind(i,'<img src="','"')
		itm={'id':id, 'title':title, 'rating':rating, 'cover':cover}
		#print itm
		L2.append(itm)
	return L2

#get_list()

def search(s):
	url='https://tt.animedia.tv/ajax/search_result/P0?limit=100&keywords='+urllib.quote_plus(s)+'&orderby_sort=entry_date|desc'
	r=GET(url)
	L=findall(r,'<div class="card__item">','<i class="ai ai-next">')
	L2=[]
	for i in L:
		id     = mfind(i,'/anime/','"')
		title  = mfind(i,'Постер аниме ','">')
		rating = mfind(i,'raitings">','/')
		cover  = mfind(i,'<img src="','"')
		if 'http' not in cover: cover='https:'+cover
		itm={'id':id, 'title':title, 'rating':rating, 'cover':cover}
		print itm
		L2.append(itm)
	return L2


def get_info(id):
	url='https://tt.animedia.tv/anime/'+id
	i=GET(url)
	
	title          = mfind(i,'<h1 class="media__post__title">','<')
	originaltitle  = mfind(i,'Оригинальное название: </br><span> ','<')
	year           = mfind(i,'года">','<')
	fanart         = mfind(i,'<li class="media__sshots__list__item"><a href="','"')
	cover          = mfind(i,'_poster"><a href="','"')
	plot           = mfind(i,'<p><p>','<')
	rating         = mfind(mfind(i,'ai-star__stroke','class'),"value='","'")
	gt             = mfind(i,'riginal-title genre-tags">','</div>')
	
	if 'http' not in fanart: fanart='https:'+fanart
	if 'http' not in cover: cover='https:'+cover
	#print gt
	Lg = findall(gt,'">','</')
	genre = ""
	for g in Lg:
		genre=genre+g.replace('">', '')+", "
	genre=genre[:-2]
	info = {
		'title':title,
		'originaltitle':originaltitle,
		'year':year,
		'fanart':fanart,
		'cover':cover,
		'plot':plot,
		'rating':rating,
		'genre':genre,
		'id':id,
		}
	#print info
	return info

#get_info('paranormalnoe-byuro-rassledovanij-muhyo-i-rodzhi')

def get_torrents(id):
	if len(id)> 1000:
		i=id
	else:
		url='https://tt.animedia.tv/anime/'+id
		i=GET(url)
	Lt=[]
	if 'tracker_info_pop_left' in i:
		L = findall(i,'<li class="tracker_info_pop_left">','</ul>')
		for t in L:
			if 'intup_left_top">' in t:
				title = mfind(t, 'intup_left_top">', '<')
				torrent = mfind(t, '</span><a href="', '"')
				magnet = 'magnet:'+mfind(t,'magnet:','"')
				itm = {'title': title , 'torrent': unlock(torrent) , 'magnet': magnet}
				Lt.append(itm)
	else:
		for t in range (1,10):
			tab='#tab'+str(t)
			if tab in i:
				sez = mfind(mfind(i, tab, '</li>'),'tab">','<')
				i2 = mfind(i, '<div id="tab'+str(t), '</i> MAGNET')
				title = sez+" - "+mfind(i2, '<h3 class="tracker_info_bold">', '<')
				torrent = mfind(i2, 'download_tracker"><a href="', '"')
				magnet = 'magnet:'+mfind(i2,'magnet:','"')
				itm = {'title': title , 'torrent': unlock(torrent) , 'magnet': magnet}
				Lt.append(itm)
	return Lt

#print get_torrents('naruto-uragannye-hroniki')
#print get_torrents('paranormalnoe-byuro-rassledovanij-muhyo-i-rodzhi')

