#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright (c) 2007 Stas Zykiewicz <stas.zytkiewicz@gmail.com>
#
#           letters-trans.py
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 3 of the GNU General Public License
# as published by the Free Software Foundation.  A copy of this license should
# be included in the file GPL-3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.


"""#########################################################################
 This is a script to translate the words used by the letters game 
 into your own language.(about 12 words)
 
 If you are finished with the translation this script will ask you 
 to send your translation to the author of childsplay so that it 
 can be included with the next release.
  
  Contact Stas Z <childsplay@users.sourceforge.net> for more info.
 
  *****************************************************************
  If you want to quit, or don't want to change anything, type Q [enter].
  *****************************************************************
  """

author = "childsplay@users.sourceforge.net"

import os,fnmatch,operator,sys,locale
from CPConstants import ASSETMLROOT

if os.environ['USER'] != 'root':
    print "\nOnly root can use this script, sorry.\n"
    sys.exit(1)

try:
    import pyassetml,pyassetmlcreator
except ImportError,info:
    print >> sys.stderr,info,"\n\n This version of childsplay depends on pyassetml"
    print >> sys.stderr, "\n You can get the pyassetml package at:","\n http://www.ofset.org/assetml"
    sys.exit(1)

if len(sys.argv) > 1:
    cwd = sys.argv[1]
else:
    cwd = ASSETMLROOT
cwd = os.path.join(cwd,'childsplay','memory-136x136')
podir = os.path.join(cwd,'po')
pofile = os.path.join(podir,'memory-136x136.pot')
if not os.path.exists(podir) or not os.path.exists(pofile):
    print "ERROR, can't find ",podir,pofile
    print "Please send this output to childsplay@users.sourceforge.net"
    print  "Childsplay will use the original (english) words in the letters game"
    sys.exit(0)

def bailout():
    print "\n You can translate the words later by running this program as root:\n python 'path-to-childsplay-dir'/letters-trans.py "
    print  " Childsplay will use the original (english) words in the letters game."
    sys.exit(0)
        
# get description names from memory assetml, these are the words used by letters.py
parser = pyassetml.AssetmlParser('childsplay/memory-136x136/memory-136x136.assetml')
loc = parser.get_locale()# get current locale setting, only the first two chars !!
wlist_org = parser.find_names((('file','.'),('description',"en")))
wlist = parser.find_names((('file','.'),('description',loc)))

#print wlist_org
#print wlist

if wlist:
    print "Already have translations in your language"
else:
    opt = pyassetmlcreator.Options()
    creator = pyassetmlcreator.Creator(cwd,opt)
    print __doc__
    podict = creator._parse_po_file(pofile)
    #print podict
    for key in podict.keys():
        prompt = 'Give the translation off: '+key+' ,or Q to quit -> '
        ans = raw_input(prompt)
        if ans == '':
            ans = key
        elif ans.upper() == 'Q':
            bailout()
        podict[key] = ans
    newpofile = [pyassetmlcreator.PO_HEADER]
    for k,v in podict.items():
        newpofile.append('msgid "%s"\n' % k)
        newpofile.append('msgstr "%s"\n\n' % v)
    stdloc = locale.setlocale(locale.LC_ALL,'')
    prompt = "\n Are these translations suitable for use with this systems\n locale setting? (%s) [y/n]" % stdloc
    ans = raw_input(prompt)
    if ans.upper() != "Y":
        print "\n Be aware that you're about to install a localization file with a\n different locale setting then your systems default."
        print " Be sure to give a valid locale.\n If you want to stop now hit 'Q'"
        prompt = " Give the locale for this translation or 'Q' to stop "
        ans = raw_input(prompt)
        if ans.upper() == "Q":
            bailout()
        else:
            stdloc = ans
    try:
        poloc = stdloc.split("_")[0]
    except ValueError:
        print " %s is not a valid locale."
        bailout()
    finalpofile = []
    for line in newpofile:
        if line.find('CHARSET') != -1:
            line = line.replace('CHARSET',stdloc,1)
        finalpofile.append(line)
    path = os.path.join(podir,poloc+'.po')
    #path = '/home/stas/temp/newpofile'
    info = creator._save_file(path,finalpofile)
    if info:
        print "\n****** Error saving/installing the file *******"
        print " The error message was:"
        print info
        bailout()
    else:
        print "\n Your translation is saved in %s" % path
    print "\n Trying to convert the assetml files."
    print " Please send any error messages generated (if any)\n to %s" % author
    creator.start()
    
    print "\n If you would like to get this translation in the next release of"
    print " childsplay then email %s to %s"% (path,author)
    print " Thank you."
    
        
print "\n That's all, enjoy"
sys.exit(0)
