#!/usr/bin/python
'''
Example:
$ gw-subtitle-adj prescale 02:44:35,067 02:44:33,067
0.999797469729
$ autogb -o utf8 < 1.srt | gw-subtitle-adj shift 2000 | gw-subtitle-adj scale 0.999797469729 > 2.srt
'''
import re, os, sys

def str2ms(instr):
    parts = instr.split(',')
    big = parts[0].split(':')
    ms = int(big[0]) * 3600000 + int(big[1]) * 60000 + int(big[2]) * 1000 + int(parts[1])
    return ms

def fix(src,l):
    '''format 1 to 001'''
    start = 0
    ret = ''
    srcstr = str(src)
    while start < (l - len(srcstr)):
        ret += '0'
        start += 1
    ret = ret + srcstr
    return ret

def ms2str(ms):
    def part1(second):
        ret = []
        ret.append(fix(second/3600,2))
        second = second - int(ret[0]) * 3600
        ret.append(fix(second/60,2))
        ret.append(fix(second - int(ret[1]) * 60,2))
        return ret
    return ','.join([':'.join(part1(ms/1000)),fix(ms%1000,3)])

def istimeline(rawstr):
    pattern = '^([0-9]{2}):([0-5]{1}[0-9]{1}):([0-5]{1}[0-9]{1}),([0-9]{3}).*$'
    return re.search(pattern,rawstr)


def convert_line(rawstr, param, action):
    def scale(ms, param):
        return int(ms * param)
    def shift(ms, param):
        return int(ms + param)
    times = rawstr.split('-->')
    newtimes = []
    for t in times:
        newtimes += [ms2str(eval(action)(str2ms(t.strip()), param))]
    return '{0} --> {1}'.format(newtimes[0], newtimes[1] + os.linesep)

def run(args, unknown_args):
    if type(args.factor) is float:
        action = 'scale'
        first = True
    else:
        action = 'shift'
        first = False
    for line in sys.stdin.readlines():
        if istimeline(line):
            if first:
                first = False
                print line.strip()
            else:
                print convert_line(line, args.factor, action).strip()
        else:
            print line.strip()

def prescale(args, unknown_args):
    print str2ms(args.timestrs[1]) / float(str2ms(args.timestrs[0]))
    

if __name__ == '__main__':
    from argparse import ArgumentParser
    master_parser = ArgumentParser()
    subparser = master_parser.add_subparsers()
    parser = subparser.add_parser('prescale', help = 'Calculate scale factor.')
    parser.add_argument('timestrs', metavar = 'str', nargs = 2, help = '''Two strings of time, the first is source string,
    the second is target string, e.g. "02:44:35,067 02:44:33,067"''')
    parser.set_defaults(func = prescale)
    parser = subparser.add_parser('scale', help = 'Scale timeline of subtitle from stdin. Time point of the first line will remain unchanged.')
    parser.add_argument('factor', metavar = 'K', type = float, help = 'Scale factor, a float number')
    parser.set_defaults(func = run)
    parser = subparser.add_parser('shift', help = 'Shift timeline of subtitle from stdin. Unit is in millisecond.')
    parser.add_argument('factor', metavar = 'N', type = int, help = 'Shift factor, an integer number')
    parser.set_defaults(func = run)
    #
    args, unknown_args = master_parser.parse_known_args()
    args.func(args, unknown_args)