from t1k.resource.draw_real_ut import draw_bscan_from_csv, csv_to_bscan_data, draw_bscan
# from t1k.resource.draw_ut import draw_bscan_real as draw_bscan_thumbview
from t1k.resource.draw_ut import draw_bscan as draw_bscan_thumbview
from t1k.resource.channel import parse_st_hit_cluster
import io
import cv2
import numpy as np
from t1k.resource.mysql_db import DB
from t1k.resource.util import llogger
path='log'
logger = llogger('drawl_frame',path)
import time
font = cv2.FONT_HERSHEY_SIMPLEX
db = DB()
db.initial_db_tb()
db.get_db_dict()

def draw_bscan_from_pos(pos_bus, convertor, top_rail, width=300, height=145, rect_option=True):
    test_desc = convertor.test_desc
    query = convertor.db.query_st_hit(pos_bus + width,
                                      pos_bus,
                                      top_rail,
                                      500, 0)
    xs, ys, chans = parse_st_hit_cluster(query)
    bscan_data = []
    for x, y, c in zip(xs, ys, chans):
        bscan_data.append((x - pos_bus, y, c))
    rect = []
    ut_recogs = convertor.db.query_ut_recog(pos_bus + width, pos_bus, top_rail)

    if not rect_option:
        rect = None

    else:

        for (ut_pos_bus, min_depth, max_depth, length) in ut_recogs:
            xmin = ut_pos_bus - pos_bus
            xmax = xmin + length
            ymin, ymax = min_depth, max_depth
            rect.append((xmin, xmax, ymin, ymax))



    img = draw_bscan(bscan_data, width, height, test_desc=test_desc, rect=rect)

    return img

def draw_bscan_from_ultra(text,convertor, width=300, height=145, rect_option=True):
    ultra_list = convertor.db.query_ultra_for_draw()
    pos_bus_list=[]
    for i in ultra_list:
        # print(i)
        pos_bus_list.append(i[0])

    # for i in range(pos_bus-100,pos_bus+500,100):
    text='text'
    for i in pos_bus_list:
        print(i)
        draw_double_frame(i, text,convertor, width, height=145, rect_option=True)

def draw_bscan_from_pos_sql_thumbview(table,pos_bus, top_rail, width=300, min_depth=0, max_depth=500):
    # test_desc = None
    query = db.query_st_hit(table, pos_bus + width,
                            pos_bus,
                            top_rail,
                            max_depth, min_depth)
    if len(query)==0:
        print('查询内容为空')
        return None #
    # print('query data')
    # print(query)
    xs, ys, chans = parse_st_hit_cluster(query)
    bscan_data = []
    for x, y, c in zip(xs, ys, chans):
        bscan_data.append((x - pos_bus, y, c))

    # img = draw_bscan_thumbview(bscan_data,width=2400,height=1590,bk_color=(0, 0, 0))
    img = draw_bscan_thumbview(bscan_data,bk_color=(0, 0, 0))
    # print('img size -- {}')
    # cv2.imwrite('image.png',img)
    return img

def draw_bscan_from_pos_sql(table,pos_bus, top_rail, width=300, min_depth=0,max_depth=500, height=145,rect_option=True,test_desc=None):
    # TODO 需要调整
    # test_desc = db.query_test_desc()
    # test_desc = None
    query = db.query_st_hit(table,pos_bus + width,
                                      pos_bus,
                                      top_rail,
                                      max_depth, min_depth)

    # if len(query)==0:
    #     return None #

    xs, ys, chans = parse_st_hit_cluster(query)
    bscan_data = []
    for x, y, c in zip(xs, ys, chans):

        if c == 'F_LER':
            y = 143
        if c == 'R_LER':
            y = 141

        bscan_data.append((x - pos_bus, y, c))
    rect = []


    if not rect_option:
        rect = None

    else:

        ut_recogs = db.query_ut_recog(table, pos_bus + width, pos_bus, top_rail)
        for ut_pos_bus, min_depth, max_depth, length in ut_recogs:
            xmin = ut_pos_bus - pos_bus
            xmax = xmin + length
            ymin, ymax = min_depth, max_depth
            rect.append((xmin, xmax, ymin, ymax))

    rect_custom = []
    ut_recogs = db.query_ut_recog_custom(table, pos_bus + width, pos_bus, top_rail)
    for ut_pos_bus, min_depth, max_depth, length in ut_recogs:
        # print(ut_recogs)
        xmin = ut_pos_bus - pos_bus
        xmax = xmin + length
        ymin, ymax = min_depth, max_depth
        rect_custom.append((xmin,xmax, ymin, ymax))



    img = draw_bscan(bscan_data, width, height, test_desc=test_desc, rect=rect,rect_custom=rect_custom)

    return img

def draw_double_frame(pos_bus, text,convertor, width, height=145, rect_option=True):
    top = draw_bscan_from_pos(pos_bus,convertor, 1, width, height, rect_option)
    bottom = draw_bscan_from_pos(pos_bus,convertor, 0, width, height, rect_option)

    padding = np.ones(shape=(30, top.shape[1], top.shape[2]))
    padding[:,:,0]=200

    edge_padding = np.zeros(shape=(100, top.shape[1], top.shape[2]))

    img = cv2.vconcat([edge_padding, top, edge_padding,padding, edge_padding, bottom, edge_padding])
    cv2.putText(img, text, (20, 200+top.shape[0]+30+30), font, 0.8, (0, 255, 255), 2)
    # print(img.shape)

    return img


def draw_double_frame_sql(pos_bus, table, text,width, height=145, rect_option=True,test_desc=None):
        # print(f'width={width}')
        top = draw_bscan_from_pos_sql(table,pos_bus, 1, width, height=height, rect_option=rect_option,test_desc=test_desc)
        bottom = draw_bscan_from_pos_sql(table,pos_bus, 0, width, height=height, rect_option=rect_option,test_desc=test_desc)

        padding = np.ones(shape=(30, top.shape[1], top.shape[2]))
        padding[:, :, 0] = 200
        edge_padding = np.zeros(shape=(100, top.shape[1], top.shape[2]))
        img = cv2.vconcat([edge_padding, top, edge_padding, padding, edge_padding, bottom, edge_padding])
        if text is not None:
            cv2.putText(img, text, (20, 200 + top.shape[0] + 30 + 30), font, 0.8, (0, 255, 255), 2)
        # h,w=img.shape[:2]
        # img=cv2.resize(img,(int(w/3),int(h/3)))
        # cv2.imwrite('test.png',img)
        return img

def draw_image_from_mysql():

    logger.info('读取sthit数据')

    pos_bus = 3000
    pos_delta = 1000
    width = 300
    fps = 24
    step = pos_delta / fps
    table='804_df090119_001'

    while 1:
        frame =draw_double_frame_sql(pos_bus, table ,'text',width=width, rect_option=True)
        frame=cv2.resize(frame,(600,400))

        cv2.imshow(f"frame", frame)

        # cv2.imwrite(f'{pos_bus}.jpg',frame)
        cv2.waitKey(4000)
        pos_bus += step
        print(f'current pos {pos_bus}')

def draw_image_from_memory():
    from t1k.resource.convertor import T1kConvertor

    t1k_convertor = T1kConvertor(r'C:\Users\byb\Desktop\804_DF090119_001.t1k', model_type="rf", version=0)
    pos_bus = 3000
    pos_delta = 1000
    print("pos_delta=", pos_delta)
    width = 200

    for data_pos, result in t1k_convertor.convert():
        pass

    print('解析完成')
    fps = 24
    step = pos_delta / fps
    while 1:
        frame = draw_double_frame(pos_bus, text='',convertor=t1k_convertor, width=width, rect_option=True)
        frame = cv2.resize(frame,(600,300))
        cv2.imshow(f"frame", frame)
        # cv2.imwrite(f'{pos_bus}.jpg',frame)
        cv2.waitKey(500)
        pos_bus += step
        print(f'current pos {pos_bus}')

def draw_image_ultra():
    from t1k.resource.convertor import T1kConvertor

    t1k_convertor = T1kConvertor(r'C:\Users\byb\Desktop\804_DF090119_001.t1k', model_type="rf", version=0)
    pos_bus = 3000
    pos_delta = 1000
    # print("pos_delta=", pos_delta)
    width = 300

    for data_pos, result in t1k_convertor.convert():
        pass
    print('解析完成')
    draw_bscan_from_ultra('测试',t1k_convertor)


def draw_thumbview():
    img=draw_bscan_from_pos_sql_thumbview('804_DF090119_001',249846,1,width=20,min_depth=10,max_depth=50)
    # img=cv2.resize(img,(600,400))
    if img is None:
        return
    cv2.imshow(f"frame", img)
    cv2.waitKey(4000)
    cv2.imwrite('frame2.png',img)
    input()

if __name__ == "__main__":
    # draw_image_from_mysql()
    draw_image_from_memory()
    # draw_image_ultra()
    # draw_thumbview()
