#!/bin/bash

specific_run()
{
    local action=$1
    if [[ $action == "list_labs" ]]
    then
	list_labs ./lab	
    elif [[ $action == emacsdevenv ]]
    then
	make -f ${JAVA_MAKEFILE} $action
    elif [[ $action == create_zip_package ]]
    then
	create_zip_package
    else
	echo "[ERROR] unrecognized specific action $action" >&2
	return
    fi
}
   
create_zip_package()
{
    dest=artloglaby/
    if [[ -e $dest ]]
    then
	echo "[ERROR] $dest already exists ! move it away ">&2
    else
	zip_package=laby.zip
	if [[ -e $zip_package ]]
	then
	    echo "[WARNING] zip package $zip_package already exists" >&2
	fi
	mkdir $dest
	# will be used at run time to save mazes
	mkdir $dest/lab
	cp scripts/laby.sh $dest
	cp LISEZMOI $dest
	cp libs/* $dest
	cp dist/lib/* $dest
	zip -r $zip_package $dest
	
	if [[ $? == 0 ]]
	then
	    rm -r $dest
	    echo "[INFO] zip package created : $zip_package"
	else
	    echo "[ERROR] zip package $zip_package creation failed" >&2
	fi
    fi
}

# first argument mandatory : directory containing generated .lab and .stl files ( usualy ./lab )
list_labs()
{
    local lab_dir=$1
    if [[ -d $lab_dir ]]
    then
	modified=0
	s=()
	properties=()
	values=()
	{
	    pushd $lab_dir
	    for stl_lab in $(ls *lab*.stl)
	    do
		if [[ $stl_lab =~ ^([^0-9]*[0-9]*x[0-9]*).stl ]]
		then
		    property=${BASH_REMATCH[1]}
		    value=$stl_lab
		    s+=("$property" "$value")
		    properties+=("$property")
		    values+=("$value")
		fi
	    done
	    s+=(exit "Exit")
	    popd
	}
	
	while true 
	do
	    property=$($DIALOG --menu "Show stl file from $lab_dir" 20 100 10 ${s[@]} 3>&1 1>&2 2>&3)
	    if [[ $? = 0 ]]
	    then
		if [[ -n $property ]]
		then
		    if [[ $property == exit ]]
		    then
			return 1
		    elif [[ $property == save ]]
		    then
			echo "TODO"
			return 0
		    fi
		    prop_len=${#properties[*]}
		    for  (( i=0; i<${prop_len}; i++ ));
		    do
			if [[ ${properties[$i]} == $property ]]
			then
			    blender --python blender_import.py -- $lab_dir/${values[$i]}
			fi
		    done

		fi
	    else
		return 2
	    fi
	done
    else
	echo "[ERROR] lab dir '$propertyfile' not found" >&2
    fi

}

# specific to laby project
if [[ ! -d lab ]]
then
    echo "[INFO] Creating directory lab to save default lab created"
    mkdir lab
fi

specific_menus+=(list_labs "Show_Labyrinth_with_blender")
specific_menus+=(create_zip_package  "Create_Zip_Package")

