#!/usr/bin/env python
import os, sys
from optparse import OptionParser
from ConfigParser import ConfigParser, NoOptionError

class KDEConfig(ConfigParser):
    # use CamelCase options
    optionxform = str

    # This may append an extra newline at the end of the file
    # but should otherwise work ok
    def write(self, fileobj):
        sections = self.sections()
        sections.sort()
        for section in sections:
            fileobj.write('[%s]\n' % section)
            options = self.options(section)
            options.sort()
            for option in options:
                fileobj.write('%s=%s\n' % (option, self.get(section, option)))
            fileobj.write('\n')
        
        

def make_new_filename(filename):
    if not filename.endswith('.kcsrc'):
        raise RuntimeError , "%s doesn't end with .kcsrc" % filename
    new_name = '%s.colors' % filename[:-6]
    if opts.verbose:
        print "New name is:", new_name
    return new_name

def set_multisect(config, option, value):
    for subsect in ['Button', 'Selection', 'Tooltip', 'View', 'Window']:
        config.set('Colors:%s' % subsect, option, value)

def merge_config(oldcfg, newcfg):
    oldsect = 'Color Scheme'
    # set name first
    name = oldcfg.get(oldsect, 'Name')
    if opts.verbose:
        print "Merging", name
    newcfg.set('General', 'Name', name)

    # handle alternateBackground
    alternateBackground = oldcfg.get(oldsect, 'alternateBackground')
    newcfg.set('Colors:Window', 'BackgroundAlternate', alternateBackground)

    # handle background
    background = oldcfg.get(oldsect, 'background')
    newcfg.set('Colors:Window', 'BackgroundNormal', background)
    
    # handle buttonBackground
    buttonBackground = oldcfg.get(oldsect, 'buttonBackground')
    newcfg.set('Colors:Button', 'BackgroundNormal', buttonBackground)

    # handle buttonForeground
    buttonForeground = oldcfg.get(oldsect, 'buttonForeground')
    newcfg.set('Colors:Button', 'ForegroundNormal', buttonForeground)

    # handle contrast
    contrast = oldcfg.get(oldsect, 'contrast')
    newcfg.set('KDE', 'contrast', contrast)

    # handle foreground
    foreground = oldcfg.get(oldsect, 'foreground')
    newcfg.set('Colors:Window', 'ForegroundNormal', foreground)

    # handle visitedLinkColor
    visited = oldcfg.get(oldsect, 'visitedLinkColor')
    set_multisect(newcfg, 'ForegroundVisited', visited)
    # handle linkColor
    linkColor = oldcfg.get(oldsect, 'linkColor')
    set_multisect(newcfg, 'ForegroundLink', linkColor)

    # handle selectBackground
    selectBackground = oldcfg.get(oldsect, 'selectBackground')
    newcfg.set('Colors:Selection', 'BackgroundNormal', selectBackground)
    # handle selectForeground
    selectForeground = oldcfg.get(oldsect, 'selectForeground')
    newcfg.set('Colors:Selection', 'ForegroundNormal', selectForeground)

    # handle shadeSortColumn
    # some of my color schemes don't have this option
    # the base config needs to have it, however
    try:
        shadeSortColumn = oldcfg.get(oldsect, 'shadeSortColumn')
    except NoOptionError:
        shadeSortColumn = newcfg.get('General', 'shadeSortColumn')
    newcfg.set('General', 'shadeSortColumn', shadeSortColumn)
    
    # handle windowBackground
    windowBackground = oldcfg.get(oldsect, 'windowBackground')
    newcfg.set('Colors:View', 'BackgroundNormal', windowBackground)
    # handle windowForeground
    windowForeground = oldcfg.get(oldsect, 'windowForeground')
    newcfg.set('Colors:View', 'ForegroundNormal', windowForeground)
    
    # activeBackground unhandled
    # activeBlend unhandled
    # activeForeground unhandled
    # activeTitleBtnBg unhandled
    # frame unhandled
    # handle unhandled (lol)
    # inactive* unhandled
    
    
    
    return newcfg

def write_config(config, filename):
    filename = os.path.expanduser(filename)
    if not filename.endswith('.colors'):
        filename = make_new_filename(filename)
    cfgfile = file(filename, 'w')
    config.write(cfgfile)
    cfgfile.close()

def make_new_file(filename):
    basecfg = KDEConfig()
    basecfg.read(opts.basefile)
    
    oldcfg = KDEConfig()
    oldcfg.read(filename)
    
    newcfg = KDEConfig()
    newcfg.read(opts.basefile)
    merge_config(oldcfg, newcfg)
    write_config(newcfg, filename)
    

BASE_SCHEME='/usr/share/kubuntu-default-settings/kde-profile/default/share/apps/color-schemes/Kubuntu.colors'
parser = OptionParser()

parser.add_option('-v', '--verbose', action='store_true', dest='verbose',
                  default=False)
parser.add_option('-b', '--base-file', action='store', dest='basefile',
                  default=BASE_SCHEME)


opts, args = parser.parse_args(sys.argv[1:])


if not args:
    raise RuntimeError , "You need to pass a filename argument, or multiple filename arguments."


    

if __name__ == '__main__':
    # python update-color-scheme.py *.kcsrc
    for arg in args:
        make_new_file(arg)
