__author__ = 'aherman'

import os
import subprocess
import applicationConfig as ac
import packagingException as pe
import repository
import pathContainers as pc


def createApplicationConfig(modulePath):
    assemblyFolderPath = os.path.abspath(modulePath)
    if assemblyFolderPath.endswith("/"):
        assemblyFolderPath = assemblyFolderPath[:-1]
    if not assemblyFolderPath.endswith("-assembly"):
        assemblyFolderPath += "-assembly"
    if not (os.path.exists(assemblyFolderPath) and os.path.isdir(assemblyFolderPath)):
        raise pe.PackagingException("{0} must be a folder and exists".format(assemblyFolderPath))
    baseDir = os.path.dirname(assemblyFolderPath)
    print "Base=" + baseDir
    print "Assembly=" + assemblyFolderPath
    applicationConfig = ac.ApplicationConfig()
    applicationConfig.revision = repository.updateRepositoryInfo(applicationConfig)
    applicationJson = assemblyFolderPath + "/application.json"
    if os.path.exists(applicationJson):
        print "Load: {0}".format(applicationJson)
        with open(applicationJson) as applicationJsonFile:
            ac.parseApplicationConfigJson(applicationJsonFile, applicationConfig)
            applicationJsonFile.close()
    ac.updateProjectModuleName(os.path.basename(modulePath), applicationConfig)
    print "Project=" + str(applicationConfig.project)
    print "Module=" + str(applicationConfig.module)
    print "Repository revision=" + str(applicationConfig.repositoryRevision)
    print "Repository url=" + str(applicationConfig.repositoryUrl)
    applicationConfig.assemblyHelper = pc.AssemblyHelper(assemblyFolderPath)
    ac.updatePackageAndVersion(applicationConfig)
    print "Package=" + str(applicationConfig.packageName)
    print "Version=" + str(applicationConfig.version)
    print "ping_disable_sleep=" + str(applicationConfig.pingDisableSleep)
    print "ports=" + str(applicationConfig.httpConfig.port) + "/" + str(applicationConfig.httpConfig.monitoringPort)
    return applicationConfig


def runMaven(applicationConfig, mvnClean=True, skipTests=True, offline=False, skipIncrementalBuild=False):
    settingsXmlPath = "{0}/settings.xml".format(os.path.abspath(applicationConfig.assemblyHelper.path + "/.."))
    command = ["mvn", "-s", settingsXmlPath, "-f", applicationConfig.assemblyHelper.pomPath]
    if mvnClean:
        command.append("clean")
    if skipTests:
        command.append("-DskipTests=true")
    if offline:
        command.append("--offline")
    if skipIncrementalBuild:
        command.append("-DnoIncrementalBuild")
    command.append("package")
    print ' '.join(command) + "\n"
    subprocess.check_call(command)


def runYaMake(applicationConfig, mvnClean=True, skipTests=True):
    yaMakeFilePath = "{0}/ya.make".format(os.path.abspath(applicationConfig.assemblyHelper.path))
    yaMakePath = os.environ.get('YA_MAKE_PATH')
    if yaMakePath is None:
         yaMakePath = "/work/arcadia/ya"

    command = [yaMakePath, "make","--target-platform", "linux", "-rj8", "--checkout"]
    if not skipTests:
        command.append("-t")
    if mvnClean:
        command.append("--clear")
    print 'Java version: ' + str(applicationConfig.javaConfig.version)
    command.append("-DJDK_VERSION=" + str(applicationConfig.javaConfig.version))
    command.append(yaMakeFilePath)
    print ' '.join(command) + "\n"
    subprocess.check_call(command)
    # recreate dirs
    subprocess.call(["rm", "-rf", applicationConfig.assemblyHelper.libFolder])
    subprocess.call(["mkdir", "-p", applicationConfig.assemblyHelper.libFolder])
    subprocess.call(["mkdir", "-p", applicationConfig.assemblyHelper.etcFolder])
    # copy artifacts to lib
    subprocess.check_call(["cp", "-r", "{0}-{1}-assembly/.".format(applicationConfig.project, applicationConfig.module),
                           applicationConfig.assemblyHelper.libFolder])
    # copy resources to etc
    subprocess.call(["cp", "-R", "{0}/src/main/resources/.".format(applicationConfig.assemblyHelper.path),
                     applicationConfig.assemblyHelper.etcFolder])


def getThisFileLocation():
    return os.path.dirname(os.path.abspath(__file__))


def copyDeployment(applicationConfig):
    etcFolder = applicationConfig.assemblyHelper.etcFolder
    assemblyBasedir = applicationConfig.assemblyHelper.path
    subprocess.call(["cp", assemblyBasedir + "/../deployment.core.json", etcFolder])
    subprocess.call(["cp", assemblyBasedir + "/../deployment.testing.json", etcFolder])
    subprocess.call(["cp", assemblyBasedir + "/../deployment.production.json", etcFolder])
    subprocess.call(["cp", assemblyBasedir + "/../deployment.development.json", etcFolder])
