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

import string, xbmc, xbmcgui, xbmcplugin, xbmcaddon, os, sys, urllib, urllib2, cookielib, time, codecs, datetime, re
import socket
import sqlite3 as db
from BeautifulSoup import BeautifulSoup, BeautifulStoneSoup
import calendar

socket.setdefaulttimeout(35000)

PLUGIN_NAME   = 'YaTv'
siteUrl = 'm.tv.yandex.ru'
httpSiteUrl = 'http://' + siteUrl
sid_file = os.path.join(xbmc.translatePath('special://temp/'), 'script.module.YaTv.cookies.sid')

addon = xbmcaddon.Addon(id='script.module.YaTv')
handle = addon.getAddonInfo('id')
__settings__ = xbmcaddon.Addon(id='script.module.YaTv')
thumb = os.path.join( addon.getAddonInfo('path'), "icon.png" )
fanart = os.path.join( addon.getAddonInfo('path'), "fanart.jpg" )
icon = os.path.join( addon.getAddonInfo('path'), 'icon.png')
db_name = os.path.join( addon.getAddonInfo('path'), "move_info.db" )
c = db.connect(database=db_name, check_same_thread=False)
cu = c.cursor()

def ru(x):return unicode(x,'utf8', 'ignore')
def xt(x):return xbmc.translatePath(x)

def showMessage(heading, message, times = 3000):
	xbmc.executebuiltin('XBMC.Notification("%s", "%s", %s, "%s")'%(heading, message, times, icon))


def GET(target, referer, post=None,cookie=None):
	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)')
		try:req.add_header('Cookie', cookie)
		except Exception, e:
			pass
		resp = urllib2.urlopen(req, timeout=50000)
		http1 = resp.read()
		try:http=http1.replace('<br />',' ').replace('<br>',' ').replace('&nbsp;','')
		except Exception, e:
			pass
		return http
	except Exception, e:
		print 'HTTP ERROR '+ target
		
def GetCookie(target, post=None):
    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)
        #print resp.read()
        cookie = resp.headers['Set-Cookie'].split(";")[0]
        return cookie
    except Exception, e:
        print e
        
tzd = {"0":"2", "-1":"3", "-2":"1", "-3":"6", "-4":"9", "-5":"10", "-6":"12", "-7":"16", "-8":"17", "-9":"18", "-10":"19", "-11":"20", "-12":"21"}

def GetCh():
    zone = str(time.timezone / 3600)
    try:
        tz = tzd[zone]
        tdelta = 0
        #print "YATV timezone="+str(time.timezone)
        #print "YATV tz="+str(tz)
    except:
        tz = "9"
        tdelta = (4*3600 + time.altzone)
        #print "YATV Except: timezone="+str(time.timezone)
        #print "YATV Except: tz="+str(tz)
    channels = ["997","998","994","996","993","734","758","328","853","314","21","916","1016","688","328","1013","140","1016","949","950","951","947","899","934","991","767","557","558","539","906","752","863","1003","900","1000","1005","970","550","548","571","926","543","547","546","509","405","564","862","730","909","542","645","924","556","863","538","625","74","809","240","901","549","965","529","967","702","942","943","751","98","917","788","339","598","392","670","904","763","887","842","536","796","910","797","911","889","845","572","402","695","748","777","145","727","761","513","790","759","481","448","773","139","348","843","696","666","663","143","664","754","455","296","382","272","457","532","111","726","737","557","504","505","692","799","353","716"]
    data = urllib.urlencode({'timezone' : tz})
    cookie = GetCookie('http://www.vsetv.com/rewrite_url.php', data)
    for ch in channels:
        dt=datetime.datetime.strftime(datetime.datetime.now() ,"%Y-%m-%d")
        s_time = ""
        f_time = ""
        title_pr = ""
        timezone = urllib.urlencode({
            'timezone' : tz,
            'submit.x' : '13',
            'submit.y' : '9',
            'selected_channel' : 'channel_'+ch+'',
            'selected_date' : 'day_'+dt+''
        })
        Url = 'http://www.vsetv.com/rewrite_url.php'
        http = GET(Url, Url, timezone, cookie)
        beautifulSoup = BeautifulSoup(http)
        el = beautifulSoup.findAll('div', attrs={'id': 'schedule_container'})
        d=[]
        prog=[]
        i=0
        if tdelta == 0:
            for gr in el:
                for g in gr:
                    if not g['class'].find('pasttime')>-1 and not g['class'].find('pastprname2')>-1 and not g['class'].find('pastdesc')>-1:
                        if g['class'].find('time')>-1 or g['class'].find('onair')>-1:
                            i+=1
                            if i==1: k=g.string.encode('utf-8')
                            f_time = g.string.encode('utf-8')
                            try:
                                if not s_time == "" and not title_pr == "":
                                    if datetime.datetime(*(time.strptime(s_time, "%H:%M")[0:6])).timetuple().tm_hour < datetime.datetime(*(time.strptime(k, "%H:%M")[0:6])).timetuple().tm_hour:
                                        start_t_d = datetime.datetime.date(datetime.datetime.today())+ datetime.timedelta(days=1)
                                    elif datetime.datetime(*(time.strptime(s_time, "%H:%M")[0:6])).timetuple().tm_hour >= datetime.datetime(*(time.strptime(k, "%H:%M")[0:6])).timetuple().tm_hour and datetime.datetime(*(time.strptime(k, "%H:%M")[0:6])).timetuple().tm_hour<5:
                                        start_t_d = datetime.datetime.date(datetime.datetime.today())+ datetime.timedelta(days=1)
                                    else:
                                        start_t_d = datetime.datetime.date(datetime.datetime.today())
                                    start_t_t = datetime.datetime.time((datetime.datetime(*(time.strptime(s_time, "%H:%M")[0:6]))))
                                    start_t1 = datetime.datetime.combine(start_t_d, start_t_t)
                                    start_t = time.mktime(start_t1.timetuple())
                                    if datetime.datetime(*(time.strptime(f_time, "%H:%M")[0:6])).timetuple().tm_hour < datetime.datetime(*(time.strptime(k, "%H:%M")[0:6])).timetuple().tm_hour:
                                        finish_t_d = datetime.datetime.date(datetime.datetime.today())+ datetime.timedelta(days=1)
                                    elif datetime.datetime(*(time.strptime(f_time, "%H:%M")[0:6])).timetuple().tm_hour >= datetime.datetime(*(time.strptime(k, "%H:%M")[0:6])).timetuple().tm_hour and datetime.datetime(*(time.strptime(k, "%H:%M")[0:6])).timetuple().tm_hour<5:
                                        finish_t_d = datetime.datetime.date(datetime.datetime.today())+ datetime.timedelta(days=1)
                                    else:
                                        finish_t_d = datetime.datetime.date(datetime.datetime.today())
                                    finish_t_t = datetime.datetime.time((datetime.datetime(*(time.strptime(f_time, "%H:%M")[0
:6]))))
                                    finish_t1 = datetime.datetime.combine(finish_t_d, finish_t_t)
                                    finish_t = time.mktime(finish_t1.timetuple())
                                    prog.append({"start":start_t, "finish":finish_t, "program":{"title":title_pr.replace("\\/","//"), "description": description.replace("\\/","//")}})
                            except Excep
tion, e:
                                print e
                            s_time = g.string.encode('utf-8')
                        elif g['class'].find('prname2')>-1:
                            try:
                                try:
                                    try:
                                        title_pr = g.string.encode('utf-8')
                                        description = ""
                                    except:
                                        title_pr = g.contents[0].encode('utf-8')
          