package com.arnaudpc;

import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

/**
 * User: ministicraft
 * Date: 04/03/2019 08:49
 */
@WebServlet("/anagram")
public class Anagram extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private List words = loadWords();

    public Anagram() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        String letters = request.getParameter("letters");
        List anagrams = getAnagrams(words, letters);
        Gson gson = new Gson();
        Return returnObj = new Return(anagrams,letters);

        out.println(gson.toJson(returnObj));
    }

    private List<String> loadWords() {
        Scanner s = null;
        List<String> list = new ArrayList<String>();

        s = new Scanner(this.getClass().getClassLoader().getResourceAsStream("/ressources/ods5.txt"));
        while (s.hasNext()){
            list.add(s.next());
        }
        s.close();

        return list;
    }

    private List<String> getAnagrams(List<String> words, String letters) {
        List<String> anagrams = new ArrayList<>();
        for (String word : words) {
            if(areAnagram(letters.toCharArray(), word.toCharArray())) anagrams.add(word);
        }
        return anagrams;
    }

    static boolean areAnagram(char[] str1, char[] str2)
    {
        // Get lenghts of both strings
        int n1 = str1.length;
        int n2 = str2.length;

        // If length of both strings is not same,
        // then they cannot be anagram
        if (n1 != n2)
            return false;

        // Sort both strings
        Arrays.sort(str1);
        Arrays.sort(str2);

        // Compare sorted strings
        for (int i = 0; i < n1; i++)
            if (str1[i] != str2[i])
                return false;

        return true;
    }

    private class Return {
        private List<String> anagrams;
        private String letters;

        public Return(List<String> anagrams, String letters) {
            this.anagrams = anagrams;
            this.letters = letters;
        }
    }

}
