# This file is located in a sub-directory to illustrate setting 
# PYTHONPATH in the tutorial, which is accessible from the 
# Help menu in Wing

import xml.sax
import xml.sax.handler

#-----------------------------------------------------------------------
class CHandler(xml.sax.handler.ContentHandler):
  """Parser handler class for parsing news from python.org"""
  
  def __init__(self):
    xml.sax.handler.ContentHandler.__init__(self)
    self.fItems = []
    self.__fCurItem = None
    self.__fText = []
    
  def startElement(self, name, attrs):
    if name == 'item':
      self.__fCurItem = {}
    self.__fText = []
    
  def endElement(self, name):
    if name == 'item':
      self.fItems.append(self.__fCurItem)
      self.__fCurItem = None
    elif self.__fCurItem is not None:
      self.__fCurItem[name] = ''.join(self.__fText).strip()
      
  def characters(self, content):
      self.__fText.append(content)
    
#-----------------------------------------------------------------------
def ParseRDFNews(txt):
  """Utility to parse XML from the python.org RDF news feed"""
  
  news = []
  
  try:
    try:
      h = CHandler()
      xml.sax.parseString(txt, h)
    except:
      # This is a common formatting error
      txt = txt.replace('&', '&amp;')
      h = CHandler()
      xml.sax.parseString(txt, h)    
  except:
    return kCannedData
  
  for item in h.fItems:
    d = ' '.join(item['pubDate'].split()[:4])
    news.append([d, item['title'], item['guid']])
    
  return news

#-----------------------------------------------------------------------
# Canned data to use when no internet connection is available
kCannedData = [
 ['Thu, 28 Feb 2019',
  'codingdirectional: Include the currency name into the forex application',
  'http://codingdirectional.info/2019/02/28/include-the-currency-name-into-the-forex-application/'],
 ['Wed, 27 Feb 2019',
  'Real Python: Traditional Face Detection With Python',
  'https://realpython.com/traditional-face-detection-python/'],
 ['Tue, 26 Feb 2019',
  "PyCoder's Weekly: Issue #357 (Feb. 26, 2019)",
  'https://pycoders.com/issues/357'],
 ['Mon, 25 Feb 2019',
  'Stack Abuse: Understanding ROC Curves with Python',
  'https://stackabuse.com/understanding-roc-curves-with-python/'],
 ['Mon, 25 Feb 2019',
  'Python Insider: Python 3.8.0a2 is now available for testing',
  'http://feedproxy.google.com/~r/PythonInsider/~3/c5jWx0k6KrQ/python-380a2-is-now-available-for.html'],
]

