from os import environ
environ['pg_HIDE_SUPPORT_PROMPT'] = '1'
import pygame as pg
def st(text, pos, color = 'main', fontid = "medium"):
    db_text = fonts[fontid].render(text, 0 if fontid == "tiny" else 1, colors[color], None)
    screen.blit(db_text, pos)
def sl(pos1, pos2, w = 2, color = 'main'):
    pg.draw.line(screen, colors[color], pos1, pos2, w)
def debug_ui():
    global sensors
    st(f"远程方位角(Z): {sensors['zangle']}", (32, 844), fontid = "tiny")
    st(f"远程滚动角(Y): {sensors['yangle']}", (32, 858), fontid = "tiny")
    st(f"远程倾斜角(X): {sensors['xangle']}", (32, 872), fontid = "tiny")
    st(f"本地滚动角(Y): {langle}", (32, 886), fontid = "tiny")
    st(f"本地倾斜角(X): {vangle}", (32, 900), fontid = "tiny")
def warn_layer(text):
    if 3 < flamenum % 15 < 12:
        st(text, (w / 2 - fonts['huge'].render(text, True, colors['warn'], None).get_w() / 2, h / 2 - 150), color=colors['warn'], fontid="huge")
def text_layer():
    global sensors, rdev
    st(f"远程主机: {remote.name}", (0, 0))
    st(f"虚拟视距: {vdist}cm", (0, 24))
    st(f"水平指示器宽度: {lw}cm", (0, 48))
    st(f"竖直指示器宽度: {round(vw)}cm", (0, 72))
    oriword = {0: "[N]", 90: "[E]", 180: "[S]", 270: "[W]"}
    for i in range(0, 13):
        st(f'{str(oriword[n] if (n := round(abs(calc_langle2(w * 0.12 + w * 0.76 * i / 12) + sensors["zangle"]))) in oriword.keys() else n).zfill(2)}', 
                (w * 0.12 + w * 0.76 * i / 12 - 12, h * 0.1 + w * 0.01))

    for i in range(0, 9):
        st(f'{str(round(abs(calc_vangle2(h * 0.25 + h * 0.5 * i / 8) - sensors["yangle"]))).zfill(2)}', 
                (w * 0.926, h * 0.25 + h * 0.49 * i / 8 - 3), fontid="small")
        st(f'{str(round(abs(calc_vangle2(h * 0.25 + h * 0.5 * i / 8) - sensors["yangle"]))).zfill(2)}', 
                (w * 0.064, h * 0.25 + h * 0.49 * i / 8 - 3), fontid="small")

    st("右副翼 >", (w * 0.95, h * 0.81), fontid="tiny")
    st(f"{dev['aile_right']}/{round(rdev['aile_right'], 1)}", (w * 0.955, h * 0.825), fontid="tiny")
    st("右尾翼 >", (w * 0.95, h * 0.93), fontid="tiny")
    st(f"{dev['tail_right']}/{round(rdev['tail_right'], 1)}", (w * 0.955, h * 0.915), fontid="tiny")
    st("左副翼 >", (w * 0.92, h * 0.81), fontid="tiny")
    st(f"{dev['aile_left']}/{round(rdev['aile_left'], 1)}", (w * 0.925, h * 0.825), fontid="tiny")
    st("左尾翼 >", (w * 0.92, h * 0.93), fontid="tiny")
    st(f"{dev['tail_left']}/{round(rdev['tail_left'], 1)}", (w * 0.925, h * 0.915), fontid="tiny")
    st("转速", (w * 0.874, h * 0.923), fontid="tiny")
    st(f"{str(dev['engine_main']).zfill(3)}", (w * 0.8745, h * 0.938), fontid="tiny")
    st("空速", (w * 0.844, h * 0.923), fontid="tiny")
    st(f"{str(sensors['speed']).zfill(3)}", (w * 0.8445, h * 0.938), fontid="tiny")
    st("能量", (w * 0.814, h * 0.923), fontid="tiny")
    st(f"{str(sensors['battery'] * 100).zfill(2)}%", (w * 0.8145, h * 0.938), fontid="tiny")
def netproc():
    while running:
        update()
        transmit("cmd", cmdgen())
        time.sleep(0.05)

if __name__ == "__main__":

    vdist = 30 # 虚拟视距
    lw = 60 # 水平指示器距离
    vw = lw * 0.5 / 0.76 # 竖直指示器距离
    pg.init()
    pg.display.set_caption(f"Azure 远程终端 - 连接到 {name}")
    flamenum = 0
    colors = {"main":"white", "remote":"green", "warn":"red"}
    fonts = {"medium":pg.font.Font('src/font.ttf', 20), "big":pg.font.Font('src/font.ttf', 40), "huge":pg.font.Font('src/font.ttf', 60), "small":pg.font.Font('src/font.ttf', 16), "tiny":pg.font.Font('src/font.ttf', 12)}

    h = 1080
    w = int(h / 9 * 16)
    hp = 1080
    wp = int(h / 9 * 16)

    screen = pg.display.set_mode((w, h), RESIZABLE)
    icon = pg.image.load("src/icon.ico").convert_alpha()
    pg.display.set_icon(icon)
    clock = pg.time.Clock()
    running = True
    pg.mouse.set_visible(False)
    pg.mouse.set_pos([w / 2, h / 2])
    f_shootmode = 0

    #welcome()
    isfullscreen = 0
    mousepos = (w / 2, h / 2)
    np = threading.Thread(target=netproc, name='NetworkProcessing')
    np.start()
    while running:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                running = False
            if event.type == pg.MOUSEMOTION:
                #loggin.info(mousepos)
                #loggin.info("鼠标: ", event.pos[0] - mousepos[0], event.pos[1] - mousepos[1])
                mousepos = event.pos
            if event.type == pg.VIDEORESIZE:
                h = event.size[1]
                w = event.size[0]
                screen = pg.display.set_mode((w, h), RESIZABLE)
        flamenum += 1
        if flamenum % 2 == 1:
            camera_refresh()
        screen.blit(frame_surface, (0, 0))
        # 计算
        vangle = calc_vangle(mousepos[1])
        langle = calc_langle(mousepos[0])
        # 常态指示器
        sl((w * 0.08, h * 0.75), (w * 0.08, h * 0.25), 2) # 高度指示
        sl((w * 0.92, h * 0.75), (w * 0.92, h * 0.25), 2) # 高度指示
        sl((w * 0.97, h * 0.86), (w * 0.95, h * 0.86), 2) # 翼面指示 1
        sl((w * 0.97, h * 0.90), (w * 0.95, h * 0.90), 2) # 翼面指示 2
        sl((w * 0.94, h * 0.86), (w * 0.92, h * 0.86), 2) # 翼面指示 1
        sl((w * 0.94, h * 0.90), (w * 0.92, h * 0.90), 2) # 翼面指示 2
        sl((w * 0.88, h * 0.1), (w * 0.12, h * 0.1), 2) # 方向指示
        sl((w / 2 - 20, h / 2), (w / 2 + 20, h / 2), 1 if not f_shootmode else 3, 'main' if not f_shootmode else 'warn') # 准星指示
        sl((w / 2, h / 2 + 20), (w / 2, h / 2 - 20), 1 if not f_shootmode else 3, 'main' if not f_shootmode else 'warn') # 准星指示

        for i in range(0, 9):
            sl((w * 0.92, h * 0.25 + h * 0.5 * i / 8), (w * 0.91, h * 0.25 + h * 0.5 * i / 8), 2) # 高度指示
            sl((w * 0.08, h * 0.25 + h * 0.5 * i / 8), (w * 0.09, h * 0.25 + h * 0.5 * i / 8), 2) # 高度指示

        for i in range(0, 13):
            sl((w * 0.12 + w * 0.76 * i / 12, h * 0.1), (w * 0.12 + w * 0.76 * i / 12, h * 0.1 + w * 0.01), 2) # 水平指示

        # 鼠标复位
        # pg.mouse.set_pos([w / 2, h / 2])

        # 指示器
        dya1 = ((w * 0.97, h * 0.86 - w * 0.01 * tan(rad(vangle)) + w * 0.01 * tan(rad(langle))), 
                (w * 0.95, h * 0.86 + w * 0.01 * tan(rad(vangle)) - w * 0.01 * tan(rad(langle))))
        dya2 = ((w * 0.97, h * 0.90 - w * 0.01 * tan(rad(vangle)) + w * 0.01 * tan(rad(langle))), 
                (w * 0.95, h * 0.90 + w * 0.01 * tan(rad(vangle)) - w * 0.01 * tan(rad(langle))))

        
        sl(dya1[0], dya1[1], 2) # 翼面指示 1
        sl(dya2[0], dya2[1], 2) # 翼面指示 2
        sl(dya3[0], dya3[1], 2) # 翼面指示 1
        sl(dya4[0], dya4[1], 2) # 翼面指示 2

        sl((w * 0.97, h * 0.86 + tan(rad(rdev['aile_left'])) * 0.01 * w), 
                (w * 0.92, h * 0.90 - tan(rad(rdev['tail_right'])) * 0.01 * w), 2, color="remote") # 翼面指示 1
        sl((w * 0.88, h * 0.92), (w * 0.88, h * 0.92 - dev['engine_main']), 20, color="main") # 转速指示 1
        sl((w * 0.82, h * 0.92), (w * 0.82, h * 0.92 - sensors["battery"] * 100), 16, color="remote") # 能量指示 1
        
        dev['aile_left'] = calc_pair2angle(dya1)
        dev['aile_right'] = calc_pair2angle(dya2)
        dev['tail_left'] = calc_pair2angle(dya3)
        dev['tail_right'] = calc_pair2angle(dya4)
        
        text_layer()
    # 键盘事件
        keys = pg.key.get_pressed()
        if keys[pg.K_ESCAPE]:
            running = 0
        if keys[pg.K_r]:
            pg.mouse.set_pos([w / 2, h / 2])
        if keys[pg.K_w]:
            pg.mouse.set_pos([mousepos[0], mousepos[1] + 3])
        if keys[pg.K_s]:
            pg.mouse.set_pos([mousepos[0], mousepos[1] - 3])
        if keys[pg.K_a]:
            pg.mouse.set_pos([mousepos[0] - 3, mousepos[1]])
        if keys[pg.K_d]:
            pg.mouse.set_pos([mousepos[0] + 3, mousepos[1]])
        if keys[pg.K_LSHIFT]:
            dev['engine_main'] += 1
        if keys[pg.K_LCTRL]:
            dev['engine_main'] -= 1
        if keys[pg.K_1]:
            warn_layer("失速警告")
        if keys[pg.K_F11]:
            if not isfullscreen:
                isfullscreen = True
                w = wp
                h = hp
                SIZE = w, h =  pg.display.list_modes()[0]
                screen = pg.display.set_mode(SIZE, FULLSCREEN)
            else:
                isfullscreen = False 
                screen = pg.display.set_mode((w, h), RESIZABLE)
        # 文字显示
        # debug
        debug_ui()
        pg.draw.circle(screen, colors['main' if not f_shootmode else 'warn'], mousepos, 2)
        pg.draw.circle(screen, colors['main'], mousepos, 20, 3) if not f_shootmode else ''
        # flip() the display to put your work on screen
        pg.display.flip()
        sl((w * 0.88, h * 0.92), (w * 0.88, h * 0.92 - dev['engine_main']), 20) # 转速指示 1
        
        dt = clock.tick(60) / 1000

    np.join()
    pg.quit()
