import os
import imp
import tempfile
import subprocess
import time
import mmap
import stat
import signal
import getopt
import getpass
import shutil
from play.utils import *
from optparse import OptionParser
# Here you can create play commands that are specific to the module, and extend existing commands

MODULE = 'nemrod'

# Commands that are specific to your module

COMMANDS = ['nemrod:import']

HELP = {
    'nemrod:import': "Import translations from Nemrod",
}

class MyOptionParser(OptionParser):
    def error(self, msg):
        pass

def execute(**kargs):
    command = kargs.get("command")
    app = kargs.get("app")
    args = kargs.get("args")
    env = kargs.get("env")
    
    parser = MyOptionParser()
    parser.add_option("-l", "--login", dest="login", help="Your login")
    parser.add_option("-p", "--pwd", dest="pwd", help="Your password")
    parser.add_option("-u", "--url", dest="url", help="Nemrod url")
    options, args = parser.parse_args(args)    
    
    app.check()
    
    projectname = app.readConf('nemrod.project.name')
    url = app.readConf('nemrod.url')
    login = app.readConf('nemrod.login')
    password = app.readConf('nemrod.password')
    languages = app.readConf('application.langs').split(',')
    defaultlang = app.readConf('nemrod.defaultlang')
    exportemptyvalues = app.readConf('nemrod.exportemptyvalues')
    onlyapprovedvalues = app.readConf('nemrod.onlyapprovedvalues')

    if options.login:
        login = options.login
    if options.pwd:
        password = options.pwd
    if options.url:
        url = options.url
    
    confpath = os.path.join(app.path, 'conf')
    
    java_args = []
    java_args.append("-Dnemrod.url=%s" % url)
    java_args.append("-Dnemrod.login=%s" % login)
    java_args.append("-Dnemrod.password=%s" % password)
    java_args.append("-Dnemrod.project=%s" % projectname)
    java_args.append("-Dnemrod.module=messages")
    java_args.append("-Dnemrod.export.workfolder=%s" % confpath)
    java_args.append("-Dnemrod.exportformat=utf8java")
    java_args.append("-Dnemrod.exportoptions.empty.values=%s" % exportemptyvalues)
    java_args.append("-Dnemrod.exportoptions.only.approved.values=%s" % onlyapprovedvalues)
    
    if command == "nemrod:import":
        print "~ Import:"
        print "~ Project: %s" % projectname
        print "~ login: %s" % login
        print "~ url: %s" % url
        nemrod_command = "-a export"
    print '~'    
    print '~'    
    
    for locale in languages:
        java_cmd = ["java" , "-Dnemrod.locale=%s" % locale] + java_args + ['-classpath', app.cp_args(), "com.nemrodsoftware.Nemrod"] + [nemrod_command]
        
        commandline=""
        for cmd_part in java_cmd:
            commandline = "%s %s" % (commandline,cmd_part)
        try:
            os.system(commandline)
            
        except OSError:
            print "Could not execute the java executable, please make sure the JAVA_HOME environment variable is set properly (the java executable should reside at JAVA_HOME/bin/java). "
            sys.exit(-1)
        print    
    
    # create the default bundle
    bundlepath = os.path.join(confpath, 'messages.%s' % defaultlang)
    defaultbundlepath = os.path.join(confpath, 'messages')
    print '~ copy %s to default bundle' % bundlepath
    shutil.copy2(bundlepath, defaultbundlepath)
 
    
# This will be executed before any command (new, run...)
def before(**kargs):
    command = kargs.get("command")
    app = kargs.get("app")
    args = kargs.get("args")
    env = kargs.get("env")


# This will be executed after any command (new, run...)
def after(**kargs):
    command = kargs.get("command")
    app = kargs.get("app")
    args = kargs.get("args")
    env = kargs.get("env")

    if command == 'new':
        try:
            print "~ Adding nemrod default configuration to application.conf"
            print "~"

            ac = open('%s/conf/application.conf' % app.path, 'r')
            conf = ac.read()
            conf = """# ------------ Nemrod ------------------
# ~~~~~
nemrod.project.name=myproject
# nemrod url
nemrod.url=http://live.nemrod-software.com/
# nemrod login
nemrod.login=myuser
# nemrod password
nemrod.password=mypwd
# export only approved values
nemrod.onlyapprovedvalues=True
# export empty values
nemrod.exportemptyvalues=False
# lang of your default bundle
nemrod.defaultlang=en
""" + conf
            ac = open('%s/conf/application.conf' % app.path, 'w')
            ac.write(conf)

        except Exception, err:
            print "~ %s" % str(err)
            print "~ "
            sys.exit(-1)

