package cbd.redis;

import redis.clients.jedis.Jedis;



import java.util.List;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Collections;

import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileNotFoundException;
 
public class A_Autocomplete {
 
	private Jedis jedis;
	public static String list = "names"; //key list for users' name
	public static String file = "names.txt"; //file with names


	public A_Autocomplete() {
		this.jedis = new Jedis();
	}
 
	    public void loadNames(String input) {

            // get the file from the resources folder
            try (InputStream file = getClass().getClassLoader().getResourceAsStream(input);
                BufferedReader reader = new BufferedReader(new InputStreamReader(file, "UTF-8"))) {
    
                if (file == null) {
                    throw new FileNotFoundException("names.txt not found");
                }
                
                List<String> namesList = new ArrayList<>();
                String line;

                //read the file and add the names to the list to sort
                while ((line = reader.readLine()) != null) {
                    namesList.add(line);
                }

                //sort the list alphabetically
                Collections.sort(namesList);

                //add sorted names to the Redis set
                for (String name : namesList) {
                    jedis.rpush(list, name);
                }


            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public List<String> getNames(String prefix) {
            List<String> allNames = jedis.lrange(list, 0, -1);
            List<String> result = new ArrayList<>();

            for (String name : allNames) {
                if (name.startsWith(prefix)) {
                    result.add(name);
                }
            }

            return result;
        }




	public static void main(String[] args) {
		A_Autocomplete auto = new A_Autocomplete();
        
		auto.jedis.del(list);
        auto.loadNames(file);

        Scanner scanner = new Scanner(System.in);
        System.out.print("Search for ('Enter for quit'): ");
        String input = scanner.nextLine();

        while (!input.isEmpty()) {
            List<String> result = auto.getNames(input);

            for (String name : result) {
                System.out.println(name);
            }
            System.out.print("Search for ('Enter for quit'): ");
            input = scanner.nextLine();
        }

        scanner.close();    
		auto.jedis.close();	
		
	}
}



