#!/usr/bin/env python
#-*- coding: UTF-8 -*-

__author__ = 'helljump'

import logging
from feedparser import parse
from PyQt4 import QtCore
import startup
from datetime import datetime
import time


log = logging.getLogger(__name__)


class RssThread(QtCore.QThread):

    popup = QtCore.pyqtSignal(unicode)

    def run(self):
        QtCore.QThread.sleep(1)
        ts = startup.CFG.value('rss/date', 0.0, int)
        latest = datetime.fromtimestamp(ts)
        entries = parse('http://zipta.ru/feed/')['entries']
        s = []
        log.debug('read news')
        for item in entries:
            link = item.links[0]['href']
            title = item.title
            text = item.summary
            date = datetime.fromtimestamp(time.mktime(item.published_parsed))
            assert isinstance(date, datetime)
            if date > latest:
                ts = max(ts, time.mktime(date.timetuple()))
                log.debug('append news %s', date)
                s.append(u'<h1>%s</h1>' % title)
                s.append(u'<p>%s</p>' % text)
                s.append(u'<p><a href="%s">Подробнее</a></p>' % link)
        if s:
            egg = u'\n'.join(s)
            self.popup.emit(egg)
            startup.CFG.setValue('rss/date', ts)


if __name__ == '__main__':
    #d = datetime(2014, 4, 1)
    #print d, time.mktime(d.timetuple())
    #ts = time.time()
    #print ts
    #print datetime.fromtimestamp(ts)
    #startup.CFG.setValue('rss/date', ts)

    ts = time.mktime(datetime(2014, 4, 15).timetuple())
    startup.CFG.setValue('rss/date', ts)

    '''
    def test(u):
        print unicode(u)

    th = RssThread()
    th.popup.connect(test)
    th.run()
    '''
