<moya xmlns="http://moyaproject.com"
      xmlns:let="http://moyaproject.com/let"
      xmlns:image="http://moyaproject.com/image"
      xmlns:fs="http://moyaproject.com/fs"
      xmlns:tn="http://moyaproject.com/thumbnail">

    <command libname="cmd.generate" synopsis="Generate thumbnails for images">
        <doc>
            Generate thumbnails for all images in a filesystem.
        </doc>
        <signature>
            <arg name="thumbnails" help="Thumbail tag to process" metavar="ELEMENT" nargs="*"/>
            <option name="overwrite" help="overwrite existing thumbnails" action="store_true" />
            <option name="all" help="process all thumbnails" action="store_true" />
        </signature>
        <let thumb_dir=".app.settings.thumb_dir" thumbnails="args.thumbnails"/>

        <if test="args.all">
            <find-elements tag="thumbnails" ns="http://moyaproject.com/thumbnail" from="${.app.name}" dst="thumbnail_elements"/>
            <let thumbnails="collect:[thumbnail_elements, 'element_ref']"/>
        </if>

        <if test="not thumbnails">
            <find-elements tag="thumbnails" ns="http://moyaproject.com/thumbnail" from="${.app.name}" dst="thumbnail_elements"/>
            <echo>One or more of the following thumbnail tags is required:</echo>
            <for src="thumbnail_elements" dst="te">
                <echo>  ${te.element_ref}</echo>
            </for>
            <exit/>
        </if>
        <list dst="failed" />
        <fs:walk-files fs="uploads" dst="files"
            files="*.jpg, *.jpeg, *.png"
            excludedirs="${thumb_dir}"/>
        <let count="len:files" />
        <for src="thumbnails" dst="thumbnail">
            <echo style="bold blue">Writing thumbnails for ${thumbnail}</echo>
            <timer console="yes">
                <progress src="list:enumerate1:files" dst="i,path" msg="generating ${basename:path}">
                    <progress-msg>thumbnail ${i} of ${count}</progress-msg>
                    <tn:generate thumbnails="${thumbnail}" path="path" overwrite="args.overwrite"/>
                    <catch exception="image.*,moya.thumbnail.*" dst="error">
                        <append src="failed" value="[path, error.msg]"/>
                    </catch>
                </progress>
            </timer>
        </for>
        <if test="failed">
            <echo>Failed to process the following files:</echo>
            <echo table="failed" header="path,error" />
        </if>
    </command>

</moya>
