#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

# txt2pot.py for Tux Paint text description files
# (based on "txt2pot.py" from `tuxpaint-stamps`)
#
# Last modified 2024-03-25
#
# Updates description localization template (".pot")
# to capture any new strings, or changes to the main English
# translations, found within the brush description files
# ("filename.txt"), which contain both the textual description
# of the brush in English, plus all languages it has been translated to.
# (As generated by "po2txt.py").

import sys, os, string
from time import gmtime, strftime

poHeader="""# Tuxpaint-brushes [Language] translation.
# Copyright (C) 2024-""".encode()+\
strftime("%Y", gmtime()).encode()+"\n".encode()+\
"""# This file is distributed under the same license as the Tuxpaint package.
# [Translator's name] <translator@email.address>, """.encode()+\
strftime("%Y", gmtime()).encode()+"\n"\
"""#
msgid ""
msgstr ""
"Project-Id-Version: tuxpaint-brushes\\n"
"Report-Msgid-Bugs-To: tuxpaint-i18n@lists.sourceforge.net\\n"
"MIME-Version: 1.0\\n"
"POT-Creation-Date: """.encode()+\
strftime("%Y-%m-%d %H:%M:%S+0000", gmtime()).encode()+"\\n\"\n"\
""""PO-Revision-Date: \\n"
"Content-Type: text/plain; charset=UTF-8\\n"
"Content-Transfer-Encoding: 8bit\\n"
""".encode()
localeList = []


def lister(poLocale, dirname, filesindir):
    filesindir.sort()
    for fname in filesindir:
        fnlist = os.path.splitext(fname)
        if fnlist[1] == ".txt":
            print(dirname + "/" + fname)
            txtFile = open(os.path.join(dirname, fname), 'rb')
            # write filename down follow mark('#').
            poFile.write(('\n#: ' + dirname + '/' + fnlist[0] + fnlist[1] + '\n').encode())
            # write description in msgid.
            line = txtFile.readline().decode()
            if line[-1:] == "\n" :
                line = line[:-1]
            line = line.replace('"', '\\"')
            print(" ==> <<" + line + ">>")
            poFile.write(('msgid "' + line + '"\n').encode())
            localeString = ""
            for lineEnc in txtFile.readlines():
                line = lineEnc.decode()
                # replace " to \"
                line = line.replace('"', '\\"')
                splitup = line.find('.utf8')
                if splitup != -1 and line[0] != '#' :
                    locale = line[:splitup]
                    if locale not in localeList:
                        localeList.append(locale)
                    if locale == poLocale:
                        localeString = line[string.find(line, "=") + 1:-1]
            txtFile.close()
            # write translation or empty string in msgstr.
            poFile.write(('msgstr "' + localeString + '"\n').encode())

if __name__ == '__main__':
    poFile = open('./tuxpaint-brushes.pot', 'wb')
    print(">>", poFile.name)
    poFile.write(poHeader)

    for root, dirs, files in sorted(os.walk('../data/brushes')):
        lister(None, root, sorted(files))

    poFile.close()
