# This script only works if this is the main process.
# This script must be executed with bash script that is located in the root directory of this project
# This is by design, and is a way to circumvent GIL of python, because the server needs to handle multiple video streaming at once.

if __name__ == "__main__":
    from ITS.api import gather_cctv_list
    from hls_streaming.hls import FrameCapturer

    import argparse
    import pandas as pd
    import time


    def refresh_hls_address(lat, lon, lat_lon_interval=0.000001):
        api_result = gather_cctv_list(
            xmin=lat - lat_lon_interval, ymin=lon - lat_lon_interval,
            xmax=lat + lat_lon_interval, ymax=lon + lat_lon_interval,
            intervals=1, roadType="its", cctvType=1
        )
        return api_result.loc[0]["cctvurl"]

    args = argparse.ArgumentParser()
    args.add_argument("--cctv_num", type=int,
                      help="Index number of cctv, to view or edit the list of cctv, see cctv_list.csv")
    args.add_argument("--interval", type=float, default=5,
                      help="Interval of frame extract of the process, unit is second, default is 5 seconds")
    args.add_argument("--video_buffer", type=float, default=15,
                      help="How may seconds of video frame buffer will be there, "
                           "default value is 15 seconds, which matches ITS video streaming packet response interval")

    args = args.parse_args()

    # This is a must, because if you refer to variables inside args directly,
    #  when ERROR happens out of that variables or related, python can not
    #  direct you to where it happens and instead unintelligible garbage
    cctv_ind = args.cctv_num
    frame_extract_interval = args.interval
    video_buffer = args.video_buffer

    cctv_info = pd.read_csv("config_files/cctv_list.csv")
    cctv_info = cctv_info.iloc[cctv_ind]

    lat = cctv_info["coordx"]
    lon = cctv_info["coordy"]
    name = cctv_info["cctvname"]
    if name.find("국도"):
        roadtype = 'its'
    else:
        roadtype = 'ex'

    # initiate ITS CCTV streaming via hls
    while True:

        cctv_url = refresh_hls_address(lat, lon, )
        print(name)
        hls_streaming = FrameCapturer(cctv_url, name, lat, lon, frame_extract_interval, video_buffer, 300, "Asia/Seoul",
                                      endpoint= "http://localhost:12345/cctv/infer")
        hls_streaming.start()

        time.sleep(60000)

        hls_streaming.stop()
