import copy


def sh_curve_summer_off(sh_array, resc=0.2):
    """
    Modifies space heating load array to be zero during non heating period
    from April to September

    Parameters
    ----------
    sh_array : np.array (of floats)
        Numpy array with space heating power in Watt (for each timestep)
    resc : float, optional
        Defines rescaling factor, related to "cut off" space heating energy
        (default: 0.2). E.g. 0.2 means, that 20 % of "cut off" space heating
        energy are used to rescale remaining demand

    Returns
    -------
    sh_array_mod : np.array (of floats)
        Numpy array holding modified space heating power in Watt (per timestep)
    """

    sh_array_mod = copy.copy(sh_array)

    timestep = int(365 * 24 * 3600 / len(sh_array_mod))

    cut_off_energy = 0

    idx_summer_start = int(114 * 24 * 3600 / timestep)
    idx_summer_stop = int(297 * 24 * 3600 / timestep)

    #  Set sh powers to zero during non heating periode
    for i in range(idx_summer_start, idx_summer_stop, 1):
        if sh_array_mod[i] > 0:
            cut_off_energy += sh_array_mod[i] * timestep / (1000 * 3600)
            sh_array_mod[i] = 0

    sh_dem_after = sum(sh_array_mod) * timestep / (1000 * 3600)

    if sh_dem_after == 0:
        resc_factor = 1
    else:
        resc_factor = (resc * cut_off_energy + sh_dem_after) / sh_dem_after

    # Rescale remaining power curve
    sh_array_mod *= resc_factor

    return sh_array_mod