package org.cloudbus.cloudsim.power;

import org.cloudbus.cloudsim.Host;
import org.cloudbus.cloudsim.Log;
import org.cloudbus.cloudsim.Vm;
import org.cloudbus.cloudsim.util.MathUtil;

import java.util.*;

public class PowerVmAllocationPolicyMigrationGHYmad extends
        PowerVmAllocationPolicyMigrationAbstract {
    /** The safety parameter in percentage (at scale from 0 to 1).
     * It is a tuning parameter used by the allocation policy to define
     * when a host is overloaded. The overload detection is based
     * on a dynamic defined host utilization threshold. This threshold
     * is computed based on the host's usage history Median absolute deviation
     * (MAD, that is similar to the Standard Deviation).
     * This safety parameter is used to increase or decrease the MAD value
     * when computing the utilization threshold.
     * As the safety parameter increases, the threshold decreases,
     * what may lead to less SLA violations. So, as higher is that parameter,
     * safer the algorithm will be when defining a host as overloaded.
     * For instance, considering a safety parameter of 1.5 (150%),
     * a host's resource usage mean is 0.5 (50%)
     * and a MAD of 0.2 (thus, the usage may vary from 0.3 to 0.7).
     * To compute the usage threshold, the MAD is increased by 50%, being equals to 0.3.
     * Finally, the threshold will be 1 - 0.3 = 0.7.
     * Thus, only when the host utilization threshold exceeds 70%,
     * the host is considered overloaded.
     * Here, more safe or less safe doesn't means a more accurate or less accurate
     * overload detection. Safer means the algorithm will use a lower host
     * utilization threshold that may lead to lower SLA violations but higher
     * resource wastage. Thus this parameter has to be tuned in order to
     * trade-off between SLA violation and resource wastage.
     */
    private double safetyParameter = 0;

    /** The fallback VM allocation policy to be used when
     * the MAD over utilization host detection doesn't have
     * data to be computed. */
    private PowerVmAllocationPolicyMigrationAbstract fallbackVmAllocationPolicy;
    public PowerVmAllocationPolicyMigrationGHYmad(
            List<? extends Host> hostList,
            PowerVmSelectionPolicy vmSelectionPolicy,
            double safetyParameter,
            PowerVmAllocationPolicyMigrationAbstract fallbackVmAllocationPolicy,
            double utilizationThreshold) {
        super(hostList, vmSelectionPolicy);
        setSafetyParameter(safetyParameter);
        setFallbackVmAllocationPolicy(fallbackVmAllocationPolicy);
    }


    public PowerVmAllocationPolicyMigrationGHYmad(
            List<? extends Host> hostList,
            PowerVmSelectionPolicy vmSelectionPolicy,
            double safetyParameter,
            PowerVmAllocationPolicyMigrationAbstract fallbackVmAllocationPolicy) {
        super(hostList, vmSelectionPolicy);
        setSafetyParameter(safetyParameter);
        setFallbackVmAllocationPolicy(fallbackVmAllocationPolicy);
    }




    @Override
    protected boolean isHostOverUtilized(PowerHost host) {
        PowerHostUtilizationHistory _host = (PowerHostUtilizationHistory) host;
        double upperThreshold = 0;
        try {
            upperThreshold = 1 - getSafetyParameter() * getHostUtilizationMad(_host);
        } catch (IllegalArgumentException e) {
            return getFallbackVmAllocationPolicy().isHostOverUtilized(host);
        }
        addHistoryEntry(host, upperThreshold);
        double totalRequestedMips = 0;
        for (Vm vm : host.getVmList()) {
            totalRequestedMips += vm.getCurrentRequestedTotalMips();
        }
        double utilization = totalRequestedMips / host.getTotalMips();
        return utilization > upperThreshold;
    }



    protected double getHostUtilizationMad(PowerHostUtilizationHistory host) throws IllegalArgumentException {
        double[] data = host.getUtilizationHistory();
        if (MathUtil.countNonZeroBeginning(data) >= 12) { // 12 has been suggested as a safe value
            return MathUtil.mad(data);
        }
        throw new IllegalArgumentException();
    }

    @Override
    protected List<Map<String, Object>> getNewVmPlacement(List<? extends Vm> vmsToMigrate, Set<? extends Host> excludedHosts){
        List<Map<String, Object>> migrationMap = new LinkedList<Map<String, Object>>();
        //关闭的主机
        List<PowerHost> switchedOffHosts = this.<PowerHost>getSwitchedOffHosts();
        //PowerVmList.sortByCpuUtilization(vmsToMigrate);
        for (Vm vm :vmsToMigrate){
            double minCriterion=Double.MIN_VALUE;
            Host allocatedHost = null;
            for (Host host :this.getHostList()){
                if ( excludedHosts.contains(host)) {
                    continue;
                }
//                if ( switchedOffHosts.contains(host)) {
//                    continue;
//                }
                //double dertaUtilizaiton  = 1 - ((PowerHost) host).getUtilizationOfCpu() - (vm.getCurrentUtilizationOfCpu() * vm.getMips()) / host.getTotalMips();

                if (host.isSuitableForVm(vm)) {
                    double power = getPowerAfterAllocation((PowerHost) host, vm);
                    double powerDiff = power - ((PowerHost) host).getPower();
                    double rwas = (getpositive(host.getUtilizaionOfCpu() - host.getUtilizationOfRam()) + 0.0001)/(host.getUtilizaionOfCpu() + host.getUtilizationOfRam());
                    double comparevalue = 0.288*(Math.exp(-powerDiff))+0.479*(1-host.getUtilizaionOfCpu())+0.174/host.getUtilizaionOfCpu();
                    if (comparevalue > minCriterion) {//谁大选谁
                        minCriterion = comparevalue;
                        allocatedHost = host;
                    }
                }


            }
            if (allocatedHost != null) {
                Log.printConcatLine("VM #", vm.getId(), " allocated to host #", allocatedHost.getId());
                Map<String, Object> migrate = new HashMap<String, Object>();
                migrate.put("vm", vm);
                migrate.put("host", allocatedHost);
                migrationMap.add(migrate);
            }
        }
        return migrationMap;
    }
    public double getpositive(double x){
        if (x >= 0){
            return x;}
        else {
            return -x;
        }
    }

    protected void setSafetyParameter(double safetyParameter) {
        if (safetyParameter < 0) {
            Log.printConcatLine("The safety parameter cannot be less than zero. The passed value is: ",
                    safetyParameter);
            System.exit(0);
        }
        this.safetyParameter = safetyParameter;
    }
    protected double getSafetyParameter() {
        return safetyParameter;
    }

    /**
     * Sets the fallback vm allocation policy.
     *
     * @param fallbackVmAllocationPolicy the new fallback vm allocation policy
     */
    public void setFallbackVmAllocationPolicy(
            PowerVmAllocationPolicyMigrationAbstract fallbackVmAllocationPolicy) {
        this.fallbackVmAllocationPolicy = fallbackVmAllocationPolicy;
    }

    /**
     * Gets the fallback vm allocation policy.
     *
     * @return the fallback vm allocation policy
     */
    public PowerVmAllocationPolicyMigrationAbstract getFallbackVmAllocationPolicy() {
        return fallbackVmAllocationPolicy;
    }


}
