import numpy as np
import math
import csv
Pt = 40
snrth = -5
Noise = - 130
# 空地信道，路损计算
def pathlossA2G(dist2,h):
    '''
    :param dist2: 基站在水平面的投影与用户的距离
    :param h:高度
    :return:空地倾斜路径损耗
    '''
    f = 1.4e9  # MHz
    d0 = 1
    c = 3e8
    alpha = 3.5
    pi = math.pi
    A = 0.25
    C = 0.39
    E = 0.25
    G = 0
    H = 0.05
    dep_tree = 2  # 植被深度
    dist3d = math.sqrt((dist2*100)**2 + h**2)
    fspl = 20 * np.log10(4 * pi * f * d0 / c) + 10 * alpha * math.log10(dist3d / d0)
    theta = math.atan2(h, dist2*100)
    slant =  A * np.power(f / math.pow(10, 6), C) * np.power(dep_tree, E) * np.power(theta + G, H)
    return fspl + slant

def pathlossA2A(BS_list):
    f = 1.4e3  # MHz
    d0 = 1
    c = 3e8
    alpha = 3.5
    pi = math.pi
    snr = np.zeros([len(BS_list),len(BS_list)])
    dist = np.zeros([len(BS_list), len(BS_list)])
    for i in range(len(BS_list)):
        for j in range(len(BS_list)):
            if j!= i:
                dist2 = math.sqrt((BS_list[i].loc[0]-BS_list[j].loc[0])**2+(BS_list[i].loc[1]-BS_list[j].loc[1])**2)
                fspl = 20 * np.log10(4 * pi * f * d0 / c) + 10 * alpha * math.log10((dist2*100) / d0)
                dist[i][j] = dist2
                snr[i][j] = BS_list[i].power_a2a - fspl -Noise
    return snr,dist


def read_list(ue_addr):
    list1 = []
    with open(ue_addr, 'r') as f:
        f = csv.reader(f, delimiter=',')
        next(f)
        for row in f:
            list1.append(row[2])
    for i in range(len(list1)):
        list1[i] = int(list1[i])
    print(len(list1))
    return list1

# pl(dB) = 10*log(pr/pt)
def dB2powerratio(dB):
    return np.power(10,dB/10)
def dBm2w(dBm):
    return 0.001*np.power(10,dBm/10)

pldB = pathlossA2G(10,100)
pl = dB2powerratio(pldB)
snr = 0.1/pl+dBm2w(Noise)
snrth = dB2powerratio(snrth)
for i in range(30):
    print(i, (0.2 / dB2powerratio(pathlossA2G(i, 200))) / dBm2w(Noise))
print(dB2powerratio(-5))

#read_list("va_solution_withBS_channel2.csv")
"""f = 1.4e9  # MHz
d0 = 1
c = 3e8
alpha = 3.5
pi = math.pi
for i in range(1,50):

    fspl = 20 * np.log10(4 * pi * f * d0 / c) + 10 * alpha * math.log10((i * 100) / d0)

    snr = Pt - fspl - Noise

    print(i, snr)
    if snr > snrth:
        print(i, snr, 'yes')"""