package dynamic.common;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

public class LoginHandler {

    public static String username = null;
    public static String password = null;

    public static void login() {

        if(!passwordFileExists()){
            try {
                System.out.print("login:");
                username = System.console().readLine();
                System.out.print("password:");
                password = new String(System.console().readPassword());

            } catch (Exception e) {
                System.out.println("username and password not entered");
                System.exit(0);
            }
        }

    }


    public static boolean passwordFileExists(){

        String home_dir = System.getenv().get("USERPROFILE");

        String password_file = home_dir + "/DELETE_ME";
        if(new File(password_file).exists()){
            getFromFile(password_file);
            return true;
        }

        password_file = home_dir + "/Desktop/DELETE_ME";
        if(new File(password_file).exists()){
            getFromFile(password_file);
            return true;
        }

        return false;

    }

    private static void getFromFile(String filename) {
        try {
            String s = FileGrabber.GrabFile(filename);
            ArrayList<String[]> strings = FileGrabber.GrabCsvFile(filename);
            username = strings.get(0)[0];
            password = strings.get(1)[0];
        } catch (IOException e) {
            System.out.println("username and password file not found - " + filename);
            System.exit(0);
        }
    }

}
