#!/usr/bin/env python
import Image,os, sys, re

__version__ = '0.1'
__copyright__ = "GPL"
__author__ = 'Philippe Normand <Philippe.Normand -at- finix (dot) eu [dot] org>'

def usage():
    print """\
A little script to convert BootSplash themes in your preferred screen resolution.

Author: %s
License: %s
Version : %s

Use it like this:

   python bootSplashThemeConvert.py oldThemeConfig.cfg newThemeConfig 1024x768 1400x1050


   - oldThemeConfig.cfg is the config for 1024x768
   - newThemeConfig will be the config for 1400x1050

Warning: converting from a 4/3 resolution (1024x768 for instance) to a bastard resolution
         like 1280x1024 which is not 4/3 will give you durty results...
""" % (__author__,__copyright__,__version__)
    sys.exit(0)

class ThemeConverter:

    reBox = re.compile('box\s+(silent\s+)?(noover\s+)?(nointer\s+)?(inter\s+)?(\d+)\s+(\d+)\s+(\d+)\s+(\d+)(.*)')

    def __init__(self, origFile, newFile, oldResol, newResol):
        self.origFile = origFile
        self.newFile = newFile
        strToInt = lambda x: int(x)
        self.oldW, self.oldH = tuple(map(strToInt,oldResol.split('x')))
        self.newW, self.newH = tuple(map(strToInt,newResol.split('x')))

    def resizeImg(self,imgFile, (width,height), newFile):
        Image.open(imgFile).resize((width,height),Image.ANTIALIAS).save(newFile)

    def regleDeTrois(self,oldNumber, oldRef, newRef):
        return (oldNumber * newRef) / oldRef

    def process_tx(self,line):
        old = int(line.split('=')[1])
        newVal = self.regleDeTrois(old, self.oldW, self.newW)
        return 'tx=%s' % newVal

    def process_ty(self, line):
        old = int(line.split('=')[1])
        newVal = self.regleDeTrois(old, self.oldH, self.newH)
        return 'ty=%s' % newVal

    def process_th(self, line):
        old = int(line.split('=')[1])
        newVal = self.regleDeTrois(old, self.oldH, self.newH)
        return 'th=%s' % newVal

    def process_tw(self, line):
        old = int(line.split('=')[1])
        newVal = self.regleDeTrois(old, self.oldW, self.newW)
        return 'tw=%s' % newVal
        
    def process_jpeg(self, line):
        imgFile = line.split('=')[1][:-1]
        newFile = os.path.join(os.path.dirname(imgFile),
                               '%sx%s.jpg' % (self.newW,self.newH))
        
        self.resizeImg(imgFile, (self.newW, self.newH), newFile)
        return 'jpeg=%s' % newFile

    def process_silentjpeg(self, line):
        imgFile = line.split('=')[1][:-1]
        newFile = os.path.join(os.path.dirname(imgFile),
                               'silent-%sx%s.jpg' % (self.newW,self.newH))
        self.resizeImg(imgFile, (self.newW, self.newH), newFile)
        return 'silentjpeg=%s' % newFile

    def process_box(self, line):
        boxMatch = self.reBox.match(line)
        result = line
        if boxMatch:
            result = 'box'
            silent, noover, nointer,inter, x1,x2,y1,y2,colors = boxMatch.groups()
            newX1 = self.regleDeTrois(int(x1), self.oldW, self.newW)
            newX2 = self.regleDeTrois(int(x2), self.oldW, self.newW)
            newY1 = self.regleDeTrois(int(y1), self.oldH, self.newH)
            newY2 = self.regleDeTrois(int(y2), self.oldH, self.newH)
            for kw in [silent, noover, inter,nointer]:
                if kw is not None:
                    result = '%s %s' % (result, kw)
            result = '%s %s %s %s %s %s' % (result, newX1, newX2, newY1, newY2,
                                            colors)
        return result

    def process(self):
        self.orig = open(origFile)
        self.new = open(newFile,'w')

        for line in self.orig.readlines():
            newLine = line
            found = False
            for keyword in ['tx','ty','th','tw','jpeg','silentjpeg','box']:
                if line.startswith(keyword):
                    callback = getattr(self, 'process_%s' % keyword)
                    newLine = callback(line) + '\n'
                    break
            self.new.write(newLine)
        self.new.close()
        self.orig.close()

if len(sys.argv) < 5:
    usage()
origFile, newFile, oldResol, newResol = sys.argv[1:]
ThemeConverter(origFile, newFile, oldResol, newResol).process()

