/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.javaone.scrambler;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.StringTokenizer;

/**
 *
 * @author jirka
 */
public class Scrambler {
    private String input;
    private int length;
    private String [] words;
    private String [] scrambles;
    public Scrambler (String text, int lenght) {
        this.input = text;
        this.length = lenght;
        analyzeString ();
    }

    public String [] getWords() {
        return words;
    }

    public String [] getScrambledWords() {
        return scrambles;
    }

    String getScrambledWord(String word) {
        char [] chars = word.toCharArray();
        char [] scrambledChars = new char [chars.length];
        Random r = new Random ();
        for (int i = 0; i < chars.length; i++) {
            int newPos = r.nextInt(length);
            while (scrambledChars[newPos] != 0) {
                newPos = r.nextInt(length);
            }
            scrambledChars[newPos] = chars[i];
        }
        return new String (scrambledChars);
    }

    private void analyzeString() {
        StringTokenizer tokenizer = new StringTokenizer(input);
        Set<String> tokens = new HashSet<String> (11);
        List<String> wordsL = new ArrayList<String> (11);
        List<String> scramblesL = new ArrayList<String> (11);
        while (tokenizer.hasMoreTokens()) {
            //String word = tokenizer.nextToken().split(" ,?!.()/\"\':;") [0].toLowerCase();
            String[] parts = tokenizer.nextToken().split("[^a-zA-Z]");
            if (parts.length == 0) continue;
            String word =  parts[0].toLowerCase();
            if (length == word.length()) {
                if (tokens.add(word)) {
                    wordsL.add(word);
                    scramblesL.add(getScrambledWord(word));
                }
            }
        }
        words = wordsL.toArray(new String[0]);
        scrambles = scramblesL.toArray(new String[0]);
    }
}
