#!/usr/bin/env python
#
# Copyright 2018 (c) Martin Owens
#
"""
Convert LibreOffice SOC Palette into a GIMP Palette file
"""

import os
import sys
import logging

from argparse import ArgumentParser

import lxml.etree

def write_palette(nom, filename, colors):
    """Write colours to a GIMP palette format"""
    print('''GIMP Palette
Name: {name}
Columns: 3
# generated by {prog}
# original file {filename}'''.format(name=nom, filename=filename, prog=sys.argv[0]))
    for color_name, color in colors:
        print("{red: >3} {green: >3} {blue: >3}\t{name}".format(red=color[0], green=color[1], blue=color[2], name=color_name))

def process_soc(filename):
    """Generator that returns each colour as a tuple of colours and names"""
    with open(filename, 'r') as fhl:
        doc = lxml.etree.parse(fhl)
        root = doc.getroot()
    for color in root:
        attr = dict([(attr.split('}')[-1], value) for attr, value in color.attrib.items()])
        if 'name' in attr and 'color' in attr:
            color = attr['color']
            color = (int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16))
            yield (attr['name'], color)

def main():
    """Main"""
    parser = ArgumentParser(description=__doc__)
    parser.add_argument('-n', '--name', help='Name of the palette', default=None)
    parser.add_argument('socfile', help='The soc file to convert')
    arg = parser.parse_args()

    if not os.path.isfile(arg.socfile):
        logging.error("Cannot find file %s", arg.socfile)
        sys.exit(1)

    if arg.name:
        name = arg.name
    else:
        name = os.path.basename(arg.socfile).rsplit('.')[0]

    write_palette(name, arg.socfile, process_soc(arg.socfile))

if __name__ == '__main__':
    main()
