import math


def calculate_open_channel_flow(channel, water_level_outside, water_level_inside):
    """
    This functions calculates discharge past a barrier in case it is connected through an open channel

    :param channel: connecting body of water between outside water level and inside water level
    :param water_level_outside: absolute height of water level on the outer (sea) side of the channel [m+MSL}
    :param water_level_inside: absolute height of water level on the inner side of the channel [m+MSL]

    :return q: discharge through the channel [m^3/m/s]
    """

    d_water = channel.Depth + (water_level_outside + water_level_inside) / 2
    diff = water_level_outside - water_level_inside
    q = 0
    if diff != 0 and d_water > 0:
        sign = diff / abs(diff)
        surf_c = channel.Width * d_water
        radius = surf_c / (2 * d_water + channel.Width)          # de Vries
        factor = 0.5
        tmp = abs(diff) / (factor + 10/(channel.Chezy**2) * channel.Length / radius) * 10 * surf_c**2
        q = sign * math.sqrt(tmp)
    return q