/*
Copyright (C) 2000-2010  Ministere de la culture et de la communication (France), AJLSM
See LICENCE file
*/
package fr.gouv.culture.sdx.utils.tests;

import java.io.File;
import java.text.DecimalFormat;

public class CurrentDirectory {

    private static final File baseDirectory = new File("U:\\temp\\sdx");


    public static void main(String[] args) throws Exception {

        int depth = Integer.parseInt(args[0]);
        int extent = Integer.parseInt(args[1]);

        // And then we prepare a decimal format according to the extent.
        int l = (new Integer(extent)).toString().length();
        StringBuffer b = new StringBuffer();
        for (int i = 0; i < l; i++) {
            b.append("0");
        }
        DecimalFormat directoryFormat = new DecimalFormat(b.toString());

        // First get the random number
        for (int jj = 0; jj < 10; jj++) {
            int ran = (int) Math.round(Math.pow(extent, depth) * Math.random()) + 1;

            // Then iterate on the levels
            String[] parts = new String[depth];
            for (int i = 1; i <= depth; i++) {
                parts[i - 1] = formatDirectory(directoryFormat, getDirectory(i, ran, depth, extent));
            }

            // Then formats the complete directory name
            StringBuffer sb = new StringBuffer(baseDirectory.getCanonicalPath());
            for (int j = 0; j < parts.length; j++) {
                sb.append(File.separator + parts[j]);
            }
            System.err.println("" + ran + ": " + (new File(sb.toString())).getCanonicalPath());
        }
    }

    /**
     * Formats a directory named by an integer.
     */
    private static String formatDirectory(DecimalFormat directoryFormat, int number) {
        return directoryFormat.format(number);
    }

    /**
     * Returns a directory number.
     */
    private static int getDirectory(int level, int dirNo, int depth, int extent) {

        /*
            Pour extent = 10 et depth = 3, si j'ai 739, je dois retourner :

                - 8 au premier
                - 4 au second
                - 9 au troisieme

            1: 8 est le ceil de la division de 739 / 100 => (739 -   0) / (extent ^ (depth-level))
            2: 4 est le ceil de la division de 39 / 10   => (739 - 700) / (extent ^ (depth-level))
            3: 9 est le ceil de la division de  9 / 1    => (739 - 730) / (extent ^ (depth-level))

            Donc la partie difficile, c'est le 0, 700, 730, etc.

                1:   0 = 0
                2: 700 = floor( ( 739 / (extent ^ 2) ) ) * (extent ^ 2)
                3: 730 = floor( ( 739 / (extent ^ 1) ) ) * (extent ^ 1)

        */

        int offset = (int) Math.floor(dirNo / Math.pow(extent, (depth - level + 1))) * (int) Math.round(Math.pow(extent, (depth - level + 1)));
        double div = (dirNo - offset) / Math.pow(extent, (depth - level));
        int ret = (int) Math.round(Math.floor(div) + 1);
        return ret;

    }
}
