package com.codegym.task.task19.task1920;

/*
The richest
The first parameter of the main method is a file name.
Each line of the specified file has the following format:
name value
where [name] is a String and [value] is a double. [name] and [value] are separated by a space.

Find the sum of all the values for each name.
Display in alphabetical order the names with the highest sum.
Separate the names with a space or new line.
Close the streams.

Example input file:
Peterson 0.501
Smith 1.35
Peterson 0.85

Example output:
Peterson


Requirements:
1. The program must NOT read data from the console.
2. The program must read the file's contents (use FileReader).
3. The file input stream (FileReader) must be closed.
4. The program should output the names with the highest sum
*/

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;

public class Solution {
    public static void main(String[] args) throws IOException {
        String fileName = args[0];
        Map<String, Double> map = new HashMap<String, Double>();
        FileReader fr = new FileReader(fileName);
        BufferedReader br = new BufferedReader(fr);
        while(br.ready()){
            String a = br.readLine();
            String[] str = a.split(" ");
            String name = str[0];
            double value = Double.parseDouble(str[1]);
            if(!map.containsKey(name)){map.put(name, value);}
            else{map.replace(name, map.get(name)+value);}
        }
        fr.close();
        br.close();


        Double maxValueInMap = (Collections.max(map.values()));
        Map<String, Double> treeMap = new TreeMap<String, Double>();
        for(Map.Entry<String, Double> entry : map.entrySet()){
            if(entry.getValue() == maxValueInMap){
//              System.out.println(entry.getKey());
                treeMap.put(entry.getKey(), entry.getValue());
            }
        }
        Set<String> keys = treeMap.keySet();
        for(String key:keys){
            System.out.println(key);
        }

    }
}