package de.duehl.basics.text.sort;

/*
 * Copyright 2019 Christian Dühl. All rights reserved.
 *
 * This program is free software. You can redistribute it and/or
 * modify it under the same terms as perl:
 *
 * general:  http://dev.perl.org/licenses/
 * GPL:      http://dev.perl.org/licenses/gpl1.html
 * artistic: http://dev.perl.org/licenses/artistic.html
 */

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.duehl.basics.text.sort.tools.SortableElement;

/**
 * Diese Klasse sortiert deutsche Worte sinnvoller als Collections.sort().
 *
 * @version 1.01     2019-04-25
 * @author Christian Dühl
 */

public class WordsSorter {

    private final List<String> words;

    private final Map<String, SortableElement> sortableByWord;

    public WordsSorter(List<String> words) {
        this.words = words;
        sortableByWord = createMap();
    }

    private Map<String, SortableElement> createMap() {
        Map<String, SortableElement> map = new HashMap<>();

        for (String word : words) {
            SortableElement sortableElement = new SortableElement(word);
            map.put(word, sortableElement);
        }

        return map;
    }

    public void sort() {
        Collections.sort(words, (word1, word2) -> compareWords(word1, word2));
    }

    private int compareWords(String word1, String word2) {
        String compare1 = sortableByWord.get(word1).getCompareWord();
        String compare2 = sortableByWord.get(word2).getCompareWord();

        int cmp = compare1.compareTo(compare2);
        if (cmp == 0) {
            cmp = word1.compareTo(word2);
        }
        return cmp;
    }

}
