<!--
	Copyright 2023-2024 MicroEJ Corp. All rights reserved.
	This library is provided in source code for use, modification and test, subject to license terms.
	Any modification of the source code will break MicroEJ Corp. warranties on the whole library.
-->

<!--
    Script to build the classpaths for the Virtual Device. It builds 2 classpaths: the Kernel classpath and the
    Features classpath.

    Inputs:
        - "application.classpath":
            - if the VD is launched with the launcher scripts, this property is empty.
            - if the VD is used to launch an application project with the "runOnSimulator" task, this property is set
              with the classpath of the application being run.
    Outputs:
        - if the VD is used as a VEE Port for a Standalone application, the "application.classpath" property will
          contain the full application classpath and the "s3.features.classpath" will be empty.
        - if the VD is used as a Kernel, the "application.classpath" property will contain the Kernel classpath,
          and the "s3.features.classpath" property will contain the classpath of all the applications launched on the
          VD. It includes the project application if the VD is used to launch an app with the "runOnSimulator" task,
          as well as all the installed applications.
-->
<project name="extension.init.vd">
    <import file="${platform.dir}/scripts/kfAntToolsDefinition.xml" optional="true"/>

    <target name="init/vd/checkEnable" depends="init/vd/init-dependencies">
        <condition property="main.class.defined">
            <and>
                <isset property="application.main.class"/>
                <not>
                    <equals arg1="${application.main.class}" arg2="com.microej.wear.kernel.Main"/>
                </not>
            </and>
        </condition>
        <condition property="onVD">
            <and>
                <isset property="onS3"/>
                <not>
                    <isset property="main.class.defined"/>
                </not>
            </and>
        </condition>
        <!-- Check if the VD contains Installed Applications -->
        <available file="${jpf.dir}/installed-applications" type="dir" property="has.installed.applications.dir"/>
        <condition property="mayContainInstalledApplications">
            <and>
                <isset property="onVD"/>
                <istrue value="${has.installed.applications.dir}"/>
            </and>
        </condition>
    </target>

    <target name="init/vd/init-dependencies">
        <taskdef resource="com/is2t/tools/application/repository/ant/antlib.xml">
            <classpath>
                <fileset dir="${jpf.dir}/tools" includes="application-repository.jar"/>
            </classpath>
        </taskdef>
    </target>

    <target name="init/vd/load-properties">
        <fail message="Could not find the Virtual Device options ('options/target.properties' file).">
            <condition>
                <not>
                    <available file="${platform.dir}/options/target.properties"/>
                </not>
            </condition>
        </fail>

        <property file="${platform.dir}/options/target.properties"/>

        <fail message="Could not find the main Application options ('main-application/application.properties' file).">
            <condition>
                <not>
                    <available file="${platform.dir}/main-application/application.properties"/>
                </not>
            </condition>
        </fail>

        <property file="${platform.dir}/main-application/application.properties"/>
    </target>

    <target unless="onVD" if="main.class.defined" name="init/vd/do-nothing" depends="init/vd/checkEnable"
            extensionOf="init/workbench">
        <echo message="The specified MicroEJ Application main class '${application.main.class}' overrides the Virtual Device Kernel main class 'com.microej.wear.kernel.Main'."></echo>
    </target>

    <target name="init/vd/installed-applications" if="mayContainInstalledApplications"
            depends="init/vd/checkEnable,init/vd/init-dependencies">
        <property description="A Comma separated list of applications ID to exclude."
                  name="vd.excluded.applications" value=""/>
        <property name="vd.installed.applications.dir" location="${platform.dir}/installed-applications"/>
        <property name="vd.additional.applications" value=""/>

        <path id="vd.installed.applications.dir.id">
            <dirset dir="${vd.installed.applications.dir}" erroronmissingdir="false"/>
            <pathelement path="${vd.additional.applications}"/>
        </path>

        <resources id="s3.features.jars.classpath"/>
        <!--
            The ApplicationsClasspath task searches applications in the given "inputpathref" locations.
            An application can be a .wpk file or a folder containing both application.metadata and release.properties.
            For each of them, it creates a value in the given "applicationsClasspathId" reference with only one path
            referencing the jar of the application.
            Therefore, the output is a reference with several value, one per application, and each value is a string
            containing the classpath of the feature (several paths separated by the OS separator).
         -->
        <ApplicationsClasspath applicationsClasspathId="s3.features.jars.classpath"
                               excludedapplications="${vd.excluded.applications}"
                               inputpathref="vd.installed.applications.dir.id"
                               output="${vd.installed.applications.dir}"/>
        <!--
            Since the resource files of a feature (.kf, .cert) are now outside of the jar, the following piece of code
            adds the whole application folder in each feature classpath, in addition to the application jar.
        -->
        <script language="javascript"><![CDATA[
            var featuresClasspaths = project.getReference('s3.features.classpath');
            var featuresJarsClasspaths = project.getReference('s3.features.jars.classpath');
            var featuresJarsClasspathsIterator = featuresJarsClasspaths.iterator();
			while (featuresJarsClasspathsIterator.hasNext()) {
                var featureJarPath = featuresJarsClasspathsIterator.next().toString();
                var unixLastSeparatorIndex = featureJarPath.lastIndexOf("/");
                var windowsLastSeparatorIndex = featureJarPath.lastIndexOf("\\");
                var lastSeparatorIndex = unixLastSeparatorIndex > windowsLastSeparatorIndex ? unixLastSeparatorIndex : windowsLastSeparatorIndex;
                var featureFolderPath = featureJarPath.substr(0, lastSeparatorIndex);
                var featureClasspath = project.createDataType('string');
                var pathSeparator = project.getProperty('path.separator');
                featureClasspath.addText(featureJarPath + pathSeparator + featureFolderPath);
                featuresClasspaths.add(featureClasspath);
            }
        ]]></script>
    </target>

    <target name="init/vd" depends="init/vd/load-properties,init/vd/installed-applications"
            extensionOf="init/workbench" if="onVD">
        <property name="vd.main.application.javalibs.resources"
                  value="/,wear-kernel-2.0.3.jar,com.microej.library.wear-wear-util-2.0.0.jar,ej.library.ui-widget-5.3.1.jar,com.microej.kernelapi-mwt-2.4.0.jar,ej.library.ui-mwt-3.6.1.jar,com.microej.kernelapi-transformed-image-painter-1.0.1.jar,com.microej.library.ui-transformed-image-painter-2.0.0.jar,com.microej.library.wear-wear-services-2.0.0.jar,com.microej.kernelapi-microvg-1.5.0.jar,ej.library.ui-motion-4.0.1.jar,com.microej.library.wear-wear-companion-server-2.0.0.jar,ej.library.iot-bluetooth-util-2.0.0.jar,ej.library.eclasspath-time-1.1.1.jar,ej.library.eclasspath-collections-1.4.2.jar,com.microej.kernelapi-trace-1.0.0.jar,ej.library.eclasspath-logging-1.2.1.jar,ej.library.runtime-basictool-1.5.0.jar,com.microej.kernelapi-bluetooth-2.3.0.jar,ej.library.iot-cbor-1.2.0.jar,ej.library.eclasspath-io-1.2.1.jar,com.microej.library.wear-wear-companion-protocol-2.0.0.jar,ej.library.runtime-message-2.2.1.jar,com.microej.kernelapi-edc-1.1.0.jar,com.microej.kernelapi-bon-1.4.0.jar,com.microej.kernelapi-kf-2.1.0.jar,com.microej.kernelapi-microui-3.6.0.jar,com.microej.kernelapi-drawing-1.1.0.jar"/>
        <property name="vd.main.application.dir" location="${platform.dir}/main-application"/>
        <pathconvert property="javalibs.classpath">
            <fileset dir="${platform.dir}/javaLibs" includes="*.jar"/>
            <fileset dir="${vm.dir}/javaLibs" includes="*.jar"
                     excludes="${applications.libs.vm.libs.excludes}"/>
        </pathconvert>
        <condition property="addFeatureToClasspath" else="false">
            <!--
                s3Standalone.microejLaunch sets application.classpath to ${platform.dir}/../resources/nls
                but this does not mean that there is an application to add to the feature classpath. So
                there is an application classpath to add to feature classpath if it is not null or set to
                this value.
            -->
            <and>
                <isset property="application.classpath"/>
                <not>
                    <equals arg1="${application.classpath}" arg2="${platform.dir}/../resources/nls"/>
                </not>
            </and>
        </condition>
        <script language="javascript">
            // Add application classpath in the features classpath
            if (project.getProperty('addFeatureToClasspath') === "true") {
            var applicationClasspath = "" + project.getProperty('application.classpath');
            var resources = project.getReference('s3.features.classpath');
            var resource = project.createDataType('string');
            resource.addText(applicationClasspath);
            resources.add(resource);
            }

            // Set VD main application classpath
            var vdMainApplicationResources = ""+project.getProperty('vd.main.application.javalibs.resources');
            var vdMainApplicationDir = ""+project.getProperty('vd.main.application.dir');
            var fileSeparator = ""+project.getProperty('file.separator');
            var pathSeparator = ""+project.getProperty('path.separator');
            var vdMainApplicationClasspath = "";
            vdMainApplicationResources.split(',').map(function(resource) {
            vdMainApplicationClasspath += project.resolveFile(vdMainApplicationDir + fileSeparator + resource) +
            pathSeparator;
            });
            var javalibsClasspath = ""+project.getProperty("javalibs.classpath");
            vdMainApplicationClasspath = vdMainApplicationClasspath + pathSeparator + javalibsClasspath;
            project.setProperty('application.classpath', vdMainApplicationClasspath);
            project.setProperty('application.main.class', 'com.microej.wear.kernel.Main');
        </script>
    </target>
</project>