package org.ut.cmldep.experiments;

import org.cloudml.core.ScalableComponent;
import org.cloudml.core.VMInstance;
import org.ut.cmldep.CMLDeployer;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Iurii on 5/4/2015.
 */
public class ExperimentLogger implements Runnable {

    private static final String FILE_EXTENSION = ".txt";
    private String fileName = "";


    public ExperimentLogger(String fileName) {
        this.fileName = fileName;
    }

    @Override
    public void run() {

        try {
            File file = new File(fileName + FILE_EXTENSION);
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
            BufferedWriter bw = new BufferedWriter(fw);


            synchronized (this) {
                bw.write(getDate());
                bw.write(prepareDataToWrite(findAllVmTypesAmount()));
            }
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String getDate() {

        String newData = "";

        Calendar cal = Calendar.getInstance();
        cal.getTime();
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");

        newData += "Time:" + timeFormat.format(cal.getTime()) + "\n";

        return newData;
    }

    private Map<String, Integer> findAllVmTypesAmount() {

        Map<String, Integer> dict = new HashMap<String, Integer>();

        CMLDeployer deployer = CMLDeployer.getSingleton();

        for (ScalableComponent scalableComponent : deployer.getModel().getScalableComponents()) {

            for (VMInstance vmInstance : scalableComponent.getListOfVMInstancesInComponent()) {

                String vmType = vmInstance.getType().getProviderSpecificTypeName();
                String newKey = scalableComponent.getName() + ":" + vmType;
                if (dict.containsKey(newKey)) {
                    Integer count = dict.get(newKey);
                    dict.put(newKey, count + 1);
                } else {
                    dict.put(newKey, 1);
                }
            }
        }
        return dict;
    }

    private String prepareDataToWrite(Map<String, Integer> data) {
        String dataForFile = "";

        for (Map.Entry<String, Integer> entry : data.entrySet()) {
            dataForFile += entry.getKey() + ":" + String.valueOf(entry.getValue()) + "\n";
        }

        return dataForFile;
    }
}
