package analyzer;

import analyzer.models.Client;

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

/**
 * This class reads the client logs, creates objects and organizes them into data structures.
 * An instance of this class must run cooperatively with an instance of class ServerLogParser
 */
public class ClientLogParser{

    public static volatile int clientRoundNo = 0;
    public static volatile boolean DONE = false;

    public static volatile int clientLineCounter = 0;
    public static volatile Map<String, Client> clients = new Hashtable<>(Analyzer.clientNo, 1);

    public static void run() {
        try {
            parse();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static void parse() throws IOException, InterruptedException {
        FileReader fr = new FileReader(Analyzer.clientLogPath);
        BufferedReader br= new BufferedReader(fr);
        String line;
        int roundLinesCount = 0;
        while((line = br.readLine()) != null) {
            clientLineCounter++;
            roundLinesCount++;

            String[] elements = line.trim().split("\t");//client-id destination timestamp
            long timestamp = Long.parseLong(elements[2]);
            String user_id = elements[0];
            //get log start time
            if(clientLineCounter == 1){
                clientRoundNo = 1;
            }
            //parse behind ServerLogParser
            while (ClientLogParser.clientRoundNo >= ServerLogParser.serverRoundNo && !ServerLogParser.DONE)
                Thread.sleep(10);

            //next round
            if(roundLinesCount == ServerLogParser.roundLineCounters.get(clientRoundNo - 1) + 1) {
                clientRoundNo++;
                roundLinesCount = 1;
            }
            addUser(user_id, clientRoundNo);

            if(ClientLogParser.clientLineCounter == ServerLogParser.serverLineCounter && ServerLogParser.DONE)
                break;
        }
        //executor.shutdown();
        System.out.println("No of Rounds " + clientRoundNo);
        System.out.println(clients.size() + " clients found");
        //printOut();;
        System.out.println();
        br.close();
        DONE = true;
    }

    private static void addUser(String id, int round) {
        Client c = clients.get(id);
        if (c == null) {
            c = new Client(id);
            clients.put(id, c);
        }
        c.addRound(ServerLogParser.rounds.get(round));
    }

    private static void printOut() {
        System.out.println("Users with hashtag " + Analyzer.toTraceHashtag + ": ");
        System.out.println("client-ID\t" + "round:posts" );
        for(Client c: clients.values()) {
            System.out.print(c.getId() + "\t");
            System.out.println(c.getRoundtoString());
        }
    }
}
