<project name="cmd-root-plugin" basedir=".">

    <target name="init-sencha-command">
        <taskdef resource="com/sencha/ant/antlib.xml" 
                 classpath="${cmd.dir}/sencha.jar"
                 loaderref="senchaloader"/>
    </target>

    <target name="init-properties">
        <property name="senchadir" value=".sencha"/>
        <property name="upgrade.temp.dir" location="${args.path}/upgrade-temp"/>
    </target>

    <target name="init" depends="init-properties,init-sencha-command">
        <x-script-def name="x-list-mvc-files" language="javascript">
            <attribute name="dir"/>
            <attribute name="property"/>
            <![CDATA[
                importPackage(java.lang);
                importPackage(java.io);
                importPackage(com.sencha.util);
                importPackage(com.sencha.logging);

                var _logger = SenchaLogManager.getLogger('x-list-mvc-files'),
                    scanDir = attributes.get('dir'),
                    propName  = attributes.get('property'),
                    dirStack = [],
                    classNames = [],
                    processFile = function(filename) {
                        var className = filename.replace(".js", ""),
                            namespace = dirStack.join('.'),
                            qualifiedName = namespace + '.' + className;
                        if(qualifiedName.indexOf('.') == 0) {
                            qualifiedName = qualifiedName.substring(1);
                        }
                        _logger.debug("Detected mvc component {}", qualifiedName);
                        classNames.push(qualifiedName);
                    },
                    walkDirectory = function(scanDir) {
                        _logger.debug("Scanning for mvc components in {}",
                            PathUtil.getAbsolutePath(scanDir));
                        var file, f, name,
                            files = scanDir.listFiles();
                        if(files) {
                            for (f = 0; f < files.length; f++) {
                                file = files[f];
                                name = file.getName();
                                _logger.debug('processing file {}',
                                    PathUtil.getAbsolutePath(file));
                                if(file.isDirectory()) {
                                    dirStack.push(name);
                                    walkDirectory(file);
                                    dirStack.pop();
                                } else {
                                    if(name.endsWith('.js')) {
                                        processFile(name);
                                    }
                                }
                            }
                        }
                    };

                walkDirectory(new File(scanDir));
                classNames.sort();
                project.setProperty(propName, classNames.join(','));
            ]]>
        </x-script-def>

    </target>

    <target name="copy-framework-to-workspace-impl">
    </target>
    <target name="-before-copy-framework-to-workspace"/>
    <target name="-after-copy-framework-to-workspace"/>
    <target name="copy-framework-to-workspace"
            depends="init,copy-framework-to-workspace-impl"
            unless="args.skipCopy"/>

    <target name="generate-workspace-impl" unless="args.skipCreate">
        <echo>generating into ${args.path} from ${cmd.config.dir}/templates/workspace</echo>
        <mkdir dir="${args.path}/packages"/>
        <x-generate dir="${cmd.config.dir}/templates/workspace"
                    todir="${args.path}">
            <param name="senchadir" value="${senchadir}"/>
        </x-generate>
    </target>
    <target name="-before-generate-workspace"/>
    <target name="-after-generate-workspace">
        <if>
            <available 
                file="${args.path}/packages/ext-theme-classic" 
                type="dir"/>
            <then>
                <if>
                    <available 
                        file="${args.path}/ext/packages/ext-theme-classic" 
                        type="dir"/>
                    <then>
                        <delete includeemptydirs="true">
                            <fileset dir="${args.path}/packages">
                                <include name="ext-theme-*/**/*"/>
                                <include name="ext-locale-*/**/*"/>
                                <include name="ext-theme-*"/>
                                <include name="ext-locale-*"/>
                            </fileset>
                        </delete>
                    </then>
                </if>
            </then>
        </if>
    </target>
    <target name="generate-workspace"
            depends="init,generate-workspace-impl"/>

    <target name="upgrade-workspace"
            depends="init">
        <x-property-file file="${workspace.config.dir}/sencha.cfg">
            <entry type="string"
                   operation="del"
                   key="ext.dir" />
            <entry type="string"
                   operation="del"
                   key="touch.dir" />
            <entry type="string"
                   operation="="
                   key="workspace.cmd.version"
                   value="${cmd.version}"/>
        </x-property-file>
        
        <if>
            <not>
                <available file="${workspace.dir}/workspace.json" />
            </not>
            <then>
                <x-generate file="${cmd.config.dir}/templates/workspace/workspace.json.tpl.default"
                            tofile="${workspace.dir}/workspace.json">
                </x-generate>
            </then>
        </if>
    </target>

    <target name="cleanup-workspace"
            depends="init">
        <for list="${workspace.cleanup.appsToRemove}" param="appToRemove">
            <sequential>
                <x-echo>Removing entry for app "@{appToRemove}"</x-echo>
                <replaceregexp file="${workspace.dir}/workspace.json" match="(\s*&quot;@{appToRemove}&quot;\s*,*)" flags="g" replace=""/>
                <replaceregexp file="${workspace.dir}/workspace.json" match="(&quot;\s*),(\s*\])" replace="\1\2"/>
                <replaceregexp file="${workspace.dir}/workspace.json" match="(&quot;)(\])" replace="\1${line.separator}    \2"/>
            </sequential>
        </for>
    </target>
    
    <target name="generate-app-impl">
        <fail>This is the default implementation from Sencha CMD and must be overriden by the framework.</fail>
    </target>
    <!--
        Fix up the base version of app.js when coming from a legacy version or crossing plugin boundaries
        
        During an upgrade, the algorithm is:
            1.) Move app.js to a temp dir
            2.) Generate the core app to update the base version of the file 
            3.) Now that the base version has been updated correctly,
                move app.js back from the temp dir to the app dir
            4.) Subsequent upgrades should, usually, be non-conflicting because we will only be
                updating the app.js files' scaffolding, which is not in locations where the user 
                will be editing the file.
    -->
    <target name="before-upgrade">
        <if>
            <equals arg1="${args.noappjs}" arg2="true"/>
            <then>
                <echo>Saving current app.js</echo>
                <property name="app.dir" value="${args.path}"/>
                <!--
                    here, we want to keep the current copy of app.js, which was originally
                    placed in ${app.dir}/app/app.js, but architect may have also placed at ${app.dir}/app.js
                -->
                <move file="${app.dir}/app/app.js" tofile="${upgrade.temp.dir}/app.js" failonerror="false" quiet="true"/>
                <move file="${app.dir}/app.js" tofile="${upgrade.temp.dir}/app.js" failonerror="false" quiet="true"/>
            </then>
        </if>
    </target>
    <target name="-after-generate-app" unless="args.skipVerStamp">
        <property name="app.dir" value="${args.path}"/>
        <x-property-file file="${app.dir}/.sencha/app/sencha.cfg">
            <entry type="string" 
                   operation="="
                   key="app.framework.version" 
                   value="${framework.version}"/>
            <entry type="string"
                   operation="="
                   key="app.cmd.version" 
                   value="${cmd.version}"/>
        </x-property-file>
    </target>
    <target name="register-app">
        <if>
            <not>
                <available file="${workspace.json.path}/workspace.json" />
            </not>
            <then>
                <x-echo level="info">Adding workspace.json file to workspace root</x-echo>
                <x-generate file="${cmd.config.dir}/templates/workspace/workspace.json.tpl.default"
                            tofile="${workspace.json.path}/workspace.json">
                </x-generate>
            </then>
        </if>
        <if>
            <not>
                <equals arg1="${workspace.json.path}" arg2="${args.path}"  />
            </not>
            <then>
                <local name="workspace.json.app.data" />
                <local name="app.reldir" />
                <x-get-relative-path from="${workspace.json.path}" to="${args.path}"
                                     property="app.reldir"/>
                <if>
                    <not>
                        <or>
                            <resourcecontains resource="${workspace.json.path}/workspace.json" substring="&quot;${app.reldir}&quot;" />
                            <contains string="${app.reldir}" substring=".tmp" />
                        </or>
                    </not>
                    <then>
                        <x-echo level="info">Adding application to workspace.json</x-echo>
                        <if>
                            <resourcecontains resource="${workspace.json.path}/workspace.json" substring="&quot;apps&quot;" />
                            <then>
                                <property name="workspace.json.app.data"><![CDATA[
        "${app.reldir}"
    ]]]></property>
                                <replaceregexp file="${workspace.json.path}/workspace.json" match="(&quot;apps&quot;\s*:\s*\[\s*)(((&quot;.*&quot;)\,*\s*)*)(\s*\])" replace="\1\2${workspace.json.app.data}" />
                                <replaceregexp file="${workspace.json.path}/workspace.json" match="&quot;\s*\n\s*&quot;" replace="&quot;\,${line.separator}        &quot;" />
                            </then>
                            <else>
                                <property name="workspace.json.app.data"><![CDATA[{
    /**
     *  An array of the paths to all the applications present in this workspace
     */
    "apps": [
        "${app.reldir}"
    ],
]]></property>
                                <replaceregexp file="${workspace.json.path}/workspace.json" match="\{" replace="${workspace.json.app.data}" />
                            </else>
                        </if>
                    </then>
                </if>
            </then>
        </if>
    </target>
    <target name="after-upgrade">
        <if>
            <equals arg1="${args.noappjs}" arg2="true"/>
            <then>
                <echo>Restoring original app.js</echo>
                <move file="${upgrade.temp.dir}/app.js" tofile="${app.dir}/app.js" failonerror="false" quiet="true"/>
                <delete dir="${upgrade.temp.dir}" failonerror="false" quiet="true"/>
            </then>
        </if>
    </target>
    <target name="refresh-generated-app">
        <x-sencha-command dir="${args.path}" inheritAll="false">
            <!--
            set the version here, as it won't be in sencha.cfg yet
            skips generating a version warning during refresh
            -->
            <property name="app.cmd.version" value="${cmd.version}"/>
            app
                refresh
        </x-sencha-command>
    </target>
    <target name="generate-app"
            depends="init,before-upgrade,generate-app-impl,after-upgrade"/>

    <!-- ****************************************************************** -->

    <target name="generate-theme-impl">
        <fail>This is the default implementation from Sencha CMD and must be overriden by the framework.</fail>
    </target>

    <target name="generate-theme"
            depends="init,generate-theme-impl"/>

    <target name="generate-controller-impl">
        <fail>This is the default implementation from Sencha CMD and must be overriden by the framework.</fail>
    </target>

    <target name="generate-controller"
            depends="init,generate-controller-impl"/>

    <target name="generate-profile-impl">
        <fail>This is the default implementation from Sencha CMD and must be overriden by the framework.</fail>
    </target>
    <target name="generate-profile"
            depends="init,generate-profile-impl"/>


    <target name="generate-model-impl">
        <fail>This is the default implementation from Sencha CMD and must be overriden by the framework.</fail>
    </target>
    <target name="generate-model"
            depends="init,generate-model-impl"/>

    <target name="generate-form-impl">
        <fail>This is the default implementation from Sencha CMD and must be overriden by the framework.</fail>
    </target>
    <target name="generate-form"
            depends="init,generate-form-impl"/>


    <target name="generate-view-impl">
        <fail>This is the default implementation from Sencha CMD and must be overriden by the framework.</fail>
    </target>
    <target name="generate-view"
            depends="init,generate-view-impl"/>
    
    <target name="app-build-impl">
        <if>
            <isset property="args.clean"/>
            <then>
                <ant dir="${app.dir}"
                     inheritall="true"
                     inheritrefs="true">
                    <target name="clean"/>
                    <target name="build"/>
                </ant>
            </then>
            <else>
                <ant dir="${app.dir}"
                     inheritall="true"
                     inheritrefs="true">
                    <target name="build"/>
                </ant>
            </else>
        </if>
    </target>
    
    <target name="app-build"
            depends="init,app-build-impl"/>

    <target name="app-clean-impl">
        <ant dir="${app.dir}"
             inheritall="true"
             inheritrefs="true">
            <target name="clean"/>
        </ant>
    </target>

    <target name="app-clean"
            depends="init,app-clean-impl"/>

    <target name="app-resolve-impl">
        <ant dir="${app.dir}"
             inheritall="true"
             inheritrefs="true"
             target="resolve">
        </ant>
    </target>
    <target name="app-resolve"
            depends="init,app-resolve-impl"/>
    
    <target name="app-watch-impl">
        <if>
            <isset property="args.clean"/>
            <then>
                <ant dir="${app.dir}"
                     inheritall="true"
                     inheritrefs="true">
                    <target name="clean"/>
                    <target name="watch"/>
                </ant>
            </then>
            <else>
                <ant dir="${app.dir}"
                     inheritall="true"
                     inheritrefs="true">
                    <target name="watch"/>
                </ant>
            </else>
        </if>
    </target>

    <target name="app-watch"
            depends="init,app-watch-impl"/>

    <target name="app-upgrade-impl">
        <fail>This is the default implementation from Sencha CMD and must be overriden by the framework.</fail>
    </target>
    <target name="-after-app-upgrade">
        <x-sencha-command dir="${app.dir}" inheritall="false">
            ant
            clean
        </x-sencha-command>
    </target>
    <target name="app-upgrade"
            depends="init,app-upgrade-impl"/>
     
    <target name="app-refresh-impl"/>
    <target name="app-refresh" depends="init">
        <echo>Refreshing app at ${args.path}</echo>
        <x-ant-call target="app-refresh-impl"/>
    </target>
    
    <macrodef name="x-upgrade">
        <attribute name="appcfg"/>
        <attribute name="workspacecfg"/>
        <sequential>
            <x-remove-timestamp file="@{appcfg}"/>
            <x-remove-timestamp file="@{workspacecfg}"/>
            
            <replaceregexp file="@{appcfg}" match="&#10;app\.cmd\.version=.*&#10;" replace=""/>
            <replaceregexp file="@{appcfg}" match="app\.id=.*&#10;" replace=""/>
        </sequential>
    </macrodef>

    <target name="app-publish-impl" depends="init" description="Publish app to Sencha Web Application Manager">
        <ant dir="${app.dir}"
             inheritall="true"
             inheritrefs="true">
            <target name="publish"/>
        </ant>
    </target>
    <target name="app-publish" depends="init,app-publish-impl"/>

    <!-- ****************************************************************** -->

    <target name="framework-add" depends="init">
        <local name="tmp.workspace.json.contents" />
        <loadfile property="tmp.workspace.json.contents" srcFile="${args.workspaceJson}" />
        <local name="worskpaceJson.data" />
        <if>
            <matches pattern="&quot;frameworks&quot;\s*:\s*\{\s*[^*]+}," string="${tmp.workspace.json.contents}" />
            <then>
                <property name="workspaceJson.data"><![CDATA[        "${args.fwKey}": ${args.fwConfig},]]></property>
                <replaceregexp file="${args.workspaceJson}" match="(&quot;frameworks&quot;\s*:\s*\{\n*)(\s*[^\}^\*]*})" replace="\1${workspaceJson.data}${line.separator}\2" flags="g" />
            </then>
            <else><property name="workspaceJson.data"><![CDATA[{
    "frameworks": {
        "${args.fwKey}": ${args.fwConfig}
    },
]]></property>
                <replaceregexp file="${args.workspaceJson}" match="\{" replace="${workspaceJson.data}"/>
            </else>
        </if>
        <replaceregexp file="${args.workspaceJson}" match=",(\s*})" replace="\1" />
    </target>
    
    <target name="framework-remove" depends="init">
        <replaceregexp file="${args.workspaceJson}" match="(s*&quot;${args.fwKey}&quot;\s*:\s*(&quot;.*&quot;,*|\{([^\}]*)\},*))" flags="g" replace=""/>
        <replaceregexp file="${args.workspaceJson}" match="(\}\s*),(\s*\})" replace="\1\2"/>
    </target>
    
    <target name="change-framework-key" depends="init">
        <x-echo>Switching framework property from "${args.oldKey}" to "${args.fwKey}" on ${args.appJson}</x-echo>
        <replaceregexp file="${args.appJson}" match="(&quot;framework&quot;\s*:\s*&quot;).*(&quot;,)" flags="g" replace="\1${args.fwKey}\2"/>
    </target>

</project>