package com.pack.modeler.structures;
/**
 *
 */

import com.googlecode.jcsv.reader.CSVEntryParser;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
* @author Saimir Bala
*
*/
public class GenericParser implements CSVEntryParser<GenericTrace> {

    private String dateformat;
    private Map<String, Integer> colIndexes;

/**
 * @throws IOException
 *
 */
    public GenericParser(Map<String, Integer> colIndexes, String format) {
        dateformat = format;
        this.colIndexes = colIndexes;
    }

    /* (non-Javadoc)
     * @see com.googlecode.jcsv.reader.CSVEntryParser#parseEntry(java.lang.String[])
     */
    @Override
    public GenericTrace parseEntry(String... data) {
        String trace = data[colIndexes.get("trace")];
        String activity = data[colIndexes.get("activity")];
        String timestamp = data[colIndexes.get("timestamp")];
        String resource = data[colIndexes.get("resource")];
        String lifecycleStr = null;
        if(colIndexes.get("lifecycle") != null)
            lifecycleStr = data[colIndexes.get("lifecycle")];
        Timestamp tStamp;

        if(timestamp.matches("\\d+")) // timestamp is a long integer
            tStamp = new Timestamp(Long.parseLong(timestamp));
        else{ //timestamp is in a date format

            String delims = "[ \\+]"; // so the delimiters are:  + - * / ^ space
            String[] tokens = timestamp.split(delims);
            String theDate = tokens[0];

            if(tokens.length > 1)
                theDate+="T"+tokens[1]+"";

            SimpleDateFormat formatter = new SimpleDateFormat(dateformat);
            Calendar cal = Calendar.getInstance();

            try {
                Date d = formatter.parse(theDate);
                cal.setTime(d);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            tStamp = new Timestamp(cal.getTimeInMillis());
        }

        // We got map with main columns  + other columns
        Map<String, String> other = new HashMap<>();
        for(Map.Entry<String, Integer> entry : colIndexes.entrySet()){
            if(!entry.getKey().equals("trace")
            && !entry.getKey().equals("activity")
            && !entry.getKey().equals("timestamp")
            && !entry.getKey().equals("lifecycle")
            && !entry.getKey().equals("resource")
            )
                other.put(entry.getKey(), data[entry.getValue()]);
        }

        return new GenericTrace(trace, activity, lifecycleStr, tStamp, resource, other);

    }

}