
# -*- coding: utf-8 -*-
import os
import sys
import subprocess
import Editor
import Project


def _init():
    global lang
    global package
    global currentFile
    global fileType
    currentFile = Editor.currentFile()
    fileType = currentFile[-2:]
    if not Editor.isValid() or currentFile == '': return
    lang = Project.targetLangCode()
    (path, pofilename) = os.path.split(Editor.currentFile())
    (package, ext) = os.path.splitext(pofilename)
    currentFile = Editor.currentFile()
    if fileType == 'po':
        complilerPresent = cmd_exists('msgfmt')
        if complilerPresent:
            actions()
        else:
            os.system('kdialog --sorry \
                "The command <msgfmt> is not available.\nYou need to install the gettext package"')
            return
    if fileType == 'ts':
        complilerPresent = cmd_exists('lrelease')
        if complilerPresent:
            saveAs()
        else:
            os.system('kdialog --sorry \
                "The command <lrelease> is not available.\nYou need to install the Qt4 development package"')
            return

def cmd_exists(cmd):
    return subprocess.call("type " + cmd, shell=True, \
        stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0

def doCompile():
    flag = False
    targetPath = variables()
    totalPath = targetPath+package+'.mo'
    if os.path.exists(totalPath):
        flag = True
        os.system('kdialog --title "The file exists!" --warningcontinuecancel "Do you want to overwrite the file?"; \
            ans=$`echo $?`; if [ "${ans:1}" -eq "0" ]; then msgfmt -o %s %s;fi' %(totalPath, currentFile))
    if not os.path.exists(targetPath):
        os.system('mkdir -p {0}'.format(targetPath))
    if not flag:
        os.system('msgfmt -o %s %s' %(totalPath, currentFile))

def saveAs():
    if fileType == 'po':
        ext = '.mo'
        compiler = 'msgfmt -o'
    if fileType == 'ts':
        ext = '.qm'
        compiler = 'lrelease -qm'
    home = os.getenv('HOME')
    output_path = home + '/' + package + ext
    cmd = ['kdialog', '--getsavefilename', output_path]
    binPath = subprocess.Popen( cmd, stdout=subprocess.PIPE ).communicate()[0]
    if binPath != '':
        binPath = binPath.rstrip()
        if os.path.exists(binPath):
            os.system('kdialog --title "The file exists!" --warningcontinuecancel "Do you want to overwrite the file?"; \
                ans=$`echo $?`; if [ "${ans:1}" -eq "0" ]; then %s %s %s;fi' %(compiler, binPath, currentFile))
        else:
            os.system('{0} {1} {2}'.format(compiler, binPath, currentFile))

def variables():
    cmd = ['kde4-config', '--localprefix']
    output = subprocess.Popen( cmd, stdout=subprocess.PIPE ).communicate()[0]
    output = output.rstrip()
    kde4path = output + 'share/locale/{0}/LC_MESSAGES/'.format(lang)
    return kde4path

def kdialogmenu():
    choice = ''
    kde4path = variables()
    string = 'Export {0}.mo to default path:\n{1}\nor choose a custom path:'.format(package,kde4path)
    try:
        choice = subprocess.check_output(['kdialog', '--combobox', string, '--default', \
            'Default path', 'Default path', 'Custom path'])
    except:
        pass
    if choice != '':
        choice = str(choice)
        choice = choice.rstrip()
    else:
        print('Canceled')
    return choice

def actions():
    choice = kdialogmenu()
    if choice == '': return
    if choice == 'Default path':
        doCompile()
    if choice == 'Custom path':
        saveAs()

_init()