#!/usr/bin/python3
# -*- coding: utf-8 -*-
# (c) 2006-2025 Joost Orchidee Winter <joostwinter@gmail.com>
# Version 0.6.1
# This program may be redistributed according to the GPL license
# (http://www.gnu.org/)

import getopt
import urllib
import urllib.error
import urllib.request
import sys
import os
import string
import re

# reload(sys)
# sys.setdefaultencoding('utf8')

PROGRAM = 0
VERSION = 1
HELP = 2

COLOUR = True	# True if you want to see colours, False if not
BLACKBG = False	# True if you always want a black background, False if not

#######################################################################
helpstring = """tt 0.6.1 (c) 2006-2025 Joost Orchidee Winter <joostwinter@gmail.com>
Distributable under the GPL

Usage: tt [options] (page|page-subpage) [(page|page-subpage) ...]

Examples:
  tt 705                # Shows page 705, including all of its subpages
  tt 705-03             # Shows subpage 3 of page 705
  tt 102 705-03 400     # Shows page 102 including all subpages, then shows
                        # subpage 3 of page 705, then shows page 400 entirely

Options:
  -h, --help            Prints this help message
  -v, --version         Prints the version number, then exits
      --color           Shows colours, regardless of the default value
                        COLOUR
      --nocolor         Does not show colours, regardless of the default value
                        COLOUR
      --blackbg         Always shows a black background, regardless of the
                        default value BLACKBG
      --noblackbg       Does not specifically show a black background,
                        regardless of the default value BLACKBG"""
#######################################################################
versionstring = """tt 0.6.1 (c) 2006-2025 Joost Orchidee Winter <joostwinter@gmail.com>
Distributable under the GPL"""
#######################################################################
usagestring = """Usage: tt [options] (page|page-subpage) [(page|page-subpage) ...]"""
#######################################################################

task = PROGRAM
scriptname = os.path.basename(sys.argv[0])

def showpage(page, subpage):
# Retrieves the page/subpage from the NOS server and displays it

  # Page retrieval into page_content
  url = 'https://teletekst-data.nos.nl/json/%3d-%02d' % (page, subpage)
  opener = urllib.request.build_opener()
  request = urllib.request.Request(url)
  request.add_header('Accept', 'text/html')
  request.add_header('Accept-Encoding', 'gzip')
  page_content = str(opener.open(request).read(),'utf8')

  # Remove everything before the frst <pre> and after the last </pre>
  begin = page_content.find("content\":\"")
  end = page_content.rfind("\"}")
  page_content = page_content[begin + 10:end]

  # Convert HTML tags into ANSI escape sequences if COLOUR is set to True
  if(COLOUR):

    colorsubstitutions = [("red", '1'),
                          ("green", '2'),
                          ("yellow", '3'),
                          ("blue", '4'),
                          ("magenta", '5'),
                          ("cyan", '6'),
                          ("white", '7')]

    for (x, y) in colorsubstitutions:
      page_content = re.sub(
        '<span class=\\\\"' + x + ' \\\\">(.*?)</span>',
        '\u001b[3' + y + 'm\\1\u001b[0m', page_content)
      page_content = re.sub(
        '<a( id=\\\\"(.*?)\\\\")? class=\\\\"' + x +
        '\\\\" href=\\\\"(.*?)\\\\">(.*?)</a>',
        '\u001b[3' + y + 'm\\4', page_content)
      for (z, w) in colorsubstitutions:
        page_content = re.sub(
          '<span class=\\\\"' + x + ' bg-' + z +
          '( doubleHeight)? \\\\">(.*?)</span>',
          '\u001b[3' + y + 'm\u001b[4' + w + 'm\\2\u001b[0m', page_content)
      page_content = re.sub(
        '<span class=\\\\"bg-' + x + '( doubleHeight)? \\\\">(.*?)</span>',
        '\u001b[4' + y + 'm\\2\u001b[0m', page_content)

# Removes the remaining tags, and replaces &gt; / &lt; with > / <

  page_content = re.sub('<(.*?)>', '', page_content)

  additional_subs = [('\\\\n', '\n'),
                     ('&gt;', '>'),
                     ('&lt;', '<'),
                     ('\\\\"', '"'),
                     ('&aacute;', u'á'),
                     ('&eacute;', u'é'),
                     ('&iacute;', u'í'),
                     ('&oacute;', u'ó'),
                     ('&uacute;', u'ú'),
                     ('&Aacute;', u'Á'),
                     ('&Eacute;', u'É'),
                     ('&Iacute;', u'Í'),
                     ('&Oacute;', u'Ó'),
                     ('&Uacute;', u'Ú'),
                     ('&agrave;', u'à'),
                     ('&egrave;', u'è'),
                     ('&igrave;', u'ì'),
                     ('&ograve;', u'ò'),
                     ('&ugrave;', u'ù'),
                     ('&Agrave;', u'À'),
                     ('&Egrave;', u'È'),
                     ('&Igrave;', u'Ì'),
                     ('&Ograve;', u'Ò'),
                     ('&Ugrave;', u'Ù'),
                     ('&acirc;', u'â'),
                     ('&ecirc;', u'ê'),
                     ('&icirc;', u'î'),
                     ('&ocirc;', u'ô'),
                     ('&ucirc;', u'û'),
                     ('&Acirc;', u'Â'),
                     ('&Ecirc;', u'Ê'),
                     ('&Icirc;', u'Î'),
                     ('&Ocirc;', u'Ô'),
                     ('&Ucirc;', u'Û'),
                     ('&auml;', u'ä'),
                     ('&euml;', u'ë'),
                     ('&iuml;', u'ï'),
                     ('&ouml;', u'ö'),
                     ('&uuml;', u'ü'),
                     ('&Auml;', u'Ä'),
                     ('&Euml;', u'Ë'),
                     ('&Iuml;', u'Ï'),
                     ('&Ouml;', u'Ö'),
                     ('&Uuml;', u'Ü'),
                     ('&atilde;', u'ã'),
                     ('&ntilde;', u'ñ'),
                     ('&otilde;', u'õ'),
                     ('&Atilde;', u'Ã'),
                     ('&Ntilde;', u'Ñ'),
                     ('&Otilde;', u'Õ'),
                     ('&ccedil;', u'ç'),
                     ('&Ccedil;', u'Ç'),
                     ('&#xF02(0|1|2|3);', ' '),
                     ('&#xF02(4|5|6|7);', u'\u2598'),
                     ('&#xF02(8|9|a|b);', u'\u259d'),
                     ('&#xF02(c|d|e|f);', u'\u2580'),
                     ('&#xF03(0|1|2|3);', u'\u2596'),
                     ('&#xF03(4|5|6|7);', u'\u258c'),
                     ('&#xF03(8|9|a|b);', u'\u259e'),
                     ('&#xF03(c|d|e|f);', u'\u259b'),
                     ('&#xF06(0|1|2|3);', u'\u2597'),
                     ('&#xF06(4|5|6|7);', u'\u259a'),
                     ('&#xF06(8|9|a|b);', u'\u2590'),
                     ('&#xF06(c|d|e|f);', u'\u259c'),
                     ('&#xF07(0|1|2|3);', u'\u2584'),
                     ('&#xF07(4|5|6|7);', u'\u2599'),
                     ('&#xF07(8|9|a|b);', u'\u259f'),
                     ('&#xF07(c|d|e|f);', u'\u2588')]

  for (x, y) in additional_subs:
    page_content = re.sub(x, y, page_content)

  # Displays the page, and...
  print(page_content, end="")
  if COLOUR: # ...if COLOUR was set, return to normal settings
    print ("\x1b[0m", end="")

# Process command line options
try:
  (opts, args) = getopt.getopt(sys.argv[1:], "vh", ["version", "help", 
		"color", "nocolor", "blackbg", "noblackbg"])
except getopt.GetoptError:
  print (scriptname + ": " + str(sys.exc_info()[1]))
  print ("Try `" + scriptname + " --help' for more information.")
  sys.exit()
for (o, a) in opts:
  if o in ("-h", "--help"):
    task = HELP
  elif o in ("-v", "--version"):
    task = VERSION
  elif o == "--color":
    COLOUR = True
  elif o == "--nocolor":
    COLOUR = False
  elif o == "--blackbg":
    BLACKBG = True
  elif o == "--noblackbg":
    BLACKBG = False
if task == HELP:
  print (helpstring)
elif task == VERSION:
  print (versionstring)
elif len(args) == 0:
  print (usagestring)
else:
  for a in args:

    subpage = 0 # will be set to something else if a is of the form ###-##

    try:
      dash_index = a.find('-')
      if(dash_index == -1):
        page = int(a)
      else:
        page = int(a[:dash_index])
        subpage = int(a[dash_index + 1:])
    except ValueError:
      print (scriptname + ": Illegal argument - " + a)
      continue

    if page < 100 or page > 899:
      print (scriptname + (": Page number (%d) must be between 100 and 899."
                          % page))
      continue

    if subpage != 0: # If a was of the form ###-##
      try:
        showpage(page, subpage)
      except urllib.HTTPError:
        print (scriptname + (": Page %d-%02d could not be found." %
				(page, subpage)))

    else: # If a was of the form ###
      while True:
        subpage = subpage + 1
        try:
          showpage(page, subpage)
        except urllib.error.HTTPError:
          if subpage == 1:
            print (scriptname + (": Page %d could not be found." % page))
          break
