#!/usr/bin/python

import sys
import re
import colorsys

def invertRGB(rgb):
  # check format
  if (re.match('^(#[0-9a-f]{6}|none)$', rgb, flags=re.IGNORECASE) == None):
    sys.stderr.write("RGB string parse error\n")
    sys.exit(1)
  
  if (rgb== "none"):
    return "none"

  rf = int(rgb[1:3], 16)/255.0
  gf = int(rgb[3:5], 16)/255.0
  bf = int(rgb[5:7], 16)/255.0

  # convert RGB to HLS
  hls = colorsys.rgb_to_hls(rf,gf,bf)
  
  # convert back with L inverted
  rgb = colorsys.hls_to_rgb(hls[0],1-hls[1],hls[2])

  R = int(255*rgb[0])
  G = int(255*rgb[1])
  B = int(255*rgb[2])
  
  return "#%02X%02X%02X" % (R,G,B)

if len(sys.argv) != 2:
  sys.stderr.write("usage: %s <inputfile>\n" % sys.argv[0])
  sys.exit(1)

ipf = open(sys.argv[1], 'r')

if ipf == None:
  sys.stderr.write("error opening inputfile: %s\n" % sys.argv[1])  
  sys.exit(1)

ipflines = ipf.readlines()
ipf.close()

def process_block(type,content):
  #print("processing type %s" %type)
  if type == "_polygon":
    sys.stdout.write("DayCustomColor:#FF0000\n")
    sys.stdout.write("NightCustomColor:#0000FF\n")
    block=content.split('\n')
    l=0
    while l < len(block):
      if block[l].startswith("Xpm"):
        xpmsize=re.search('Xpm *= *"([0-9]+) +([0-9]+) +([0-9]+) +([0-9]+)"', block[l], re.IGNORECASE)
        colcount = 2*int(xpmsize.group(3))
        sys.stdout.write('Xpm="%s %s %d %s"\n' %(xpmsize.group(1),xpmsize.group(2),colcount,xpmsize.group(4)))
        l+=1
        sys.stdout.write(block[l]+'\n')
        if (colcount == 2):
          c0=re.search('". c (#[0-9a-f]{6}|none)"', block[l], re.IGNORECASE).group(1)
          sys.stdout.write('"3 c '+invertRGB(c0)+'"\n')
        if (colcount == 4):
          c0=re.search('". c (#[0-9a-f]{6}|none)"', block[l], re.IGNORECASE).group(1)
          l+=1
          sys.stdout.write(block[l]+'\n')
          c1=re.search('". c (#[0-9a-f]{6}|none)"', block[l], re.IGNORECASE).group(1)
          sys.stdout.write('"3 c '+invertRGB(c0)+'"\n')
          sys.stdout.write('"4 c '+invertRGB(c1)+'"\n')
      else:
        sys.stdout.write(block[l]+'\n')
        if block[l].startswith("DaycustomColor"):
          dcc = re.search('DayCustomColor\s*:\s*(#[0-9a-f]{6})$', block[l], flags=re.IGNORECASE).group(1)
          sys.stdout.write("NightcustomColor:"+invertRGB(dcc)+'\n')
      l+=1
    return
  if type == "_point":
    sys.stdout.write("DayCustomColor:#FF0000\n")
    sys.stdout.write("NightCustomColor:#0000FF\n")
    block=content.split('\n')
    l=0
    while l < len(block):
      if block[l].startswith("DayXpm"):
        xpm_len = re.search('DayXpm *= *"([0-9]+) +([0-9]+) +([0-9]+) +([0-9]+)".*', block[l], re.IGNORECASE)
        # print("%s %s %s %s" % (xpm_len.group(1),xpm_len.group(2),xpm_len.group(3),xpm_len.group(4)))
        sys.stdout.write(block[l]+'\n')
        nitexpm=block[l].replace("DayXpm","NightXpm")+'\n'
        for i in range(0,int(xpm_len.group(3))):
          l+=1
          sys.stdout.write(block[l]+'\n')
          res=re.search('(".\s+c\s+)(#[0-9a-f]{6}|none)"', block[l], re.IGNORECASE)
          nitexpm+=res.group(1)+invertRGB(res.group(2))+'"\n'
        for i in range(0,int(xpm_len.group(2))):
          l+=1
          sys.stdout.write(block[l]+'\n')
          nitexpm+=block[l]+'\n'
        sys.stdout.write(nitexpm)
      else:
        sys.stdout.write(block[l]+'\n')
        if block[l].startswith("DaycustomColor"):
          dcc = re.search('DaycustomColor\s*:\s*(#[0-9a-f]{6})$', block[l], flags=re.IGNORECASE).group(1)
          sys.stdout.write("NightcustomColor:"+invertRGB(dcc)+'\n')
      l+=1
    return    
  if type == "_line":
    sys.stdout.write("DaycustomColor:#FF0000\n")
    sys.stdout.write("NightCustomColor:#0000FF\n")
    block=content.split('\n')
    l=0
    while l < len(block):
      if block[l].startswith("Xpm"):
        xpmsize=re.search('Xpm *= *"([0-9]+) +([0-9]+) +([0-9]+) +([0-9]+)"', block[l], re.IGNORECASE)
        colcount = 2*int(xpmsize.group(3))
        if colcount == 8:
          colcount = 4
        sys.stdout.write('Xpm="%s %s %d %s"\n' %(xpmsize.group(1),xpmsize.group(2),colcount,xpmsize.group(4)))
        l+=1
        sys.stdout.write(block[l]+'\n')
        if (colcount == 2):
          c0=re.search('". c (#[0-9a-f]{6}|none)"', block[l], re.IGNORECASE).group(1)
          sys.stdout.write('"3 c '+invertRGB(c0)+'"\n')
        if (colcount == 4):
          c0=re.search('". c (#[0-9a-f]{6}|none)"', block[l], re.IGNORECASE).group(1)
          l+=1
          sys.stdout.write(block[l]+'\n')
          c1=re.search('". c (#[0-9a-f]{6}|none)"', block[l], re.IGNORECASE).group(1)
          sys.stdout.write('"3 c '+invertRGB(c0)+'"\n')
          sys.stdout.write('"4 c '+invertRGB(c1)+'"\n')
      else:
        sys.stdout.write(block[l]+'\n')
        if block[l].startswith("DaycustomColor"):
          dcc = re.search('DaycustomColor\s*:\s*(#[0-9a-f]{6})$', block[l], flags=re.IGNORECASE).group(1)
          sys.stdout.write("NightcustomColor:"+invertRGB(dcc)+'\n')
      l+=1
    return
  
  # generic fallback
  if (content != ""):
    sys.stdout.write(content+'\n')

inside_block = None
block_content=""
# lines including \n
for line in ipflines:
  line = line.strip()
  
  if line.startswith("CustomColor="):
    #line="CustomColor=DayAndNight"
    continue
  
  # ignore NightcustomColor as we deal with day-only inputfiles
  if line.startswith("NightcustomColor"):
    continue
  
  if line.startswith("[_"):
    inside_block = line.strip('[]')
    # block header
    sys.stdout.write('['+inside_block+']\n')
    continue

  if line.lower().startswith("[end]"):
    process_block(inside_block,block_content.strip())
    sys.stdout.write(line+'\n')
    block_content=""
    inside_block = None
    continue

  if inside_block is None:
    sys.stdout.write(line+'\n')
  else:
    block_content+=line+'\n'

