from pathlib import Path
import os
import cv2
import numpy as np
import pandas as pd
from pupil_labs.dynamic_content_on_rim.uitools.ui_tools import get_path, get_savedir
from pupil_labs.dynamic_content_on_rim.video.read import get_frame, read_video_ts


input_path = '.../raw-data-export-2023-09-05_11-56-16/2023-09-05_11-56-16-72b5f845'

# Format to read timestamps
oftype = {"timestamp [ns]": np.uint64}

# Read the timestamps
world_timestamps_df = pd.read_csv(
    os.path.join(input_path, "world_timestamps.csv"), dtype=oftype)

events_df = pd.read_csv(os.path.join(input_path, "events.csv"), dtype=oftype)
gaze_df = pd.read_csv(os.path.join(input_path, "gaze.csv"), dtype=oftype)


video_path = os.path.join(input_path, "e1b51f12_0.0-1443.113.mp4")

_, frames, pts, ts = read_video_ts(video_path)

ts = (world_timestamps_df["timestamp [ns]"])

gaze_df.rename(
            {
                "gaze_timestamp": "timestamp [ns]",
                "norm_pos_x": "gaze x [px]",
                "norm_pos_y": "gaze y [px]", }, axis=1, inplace=True,)

gaze_df["timestamp [ns]"] = gaze_df["timestamp [ns]"].map(lambda x: x * 1e9)
ts = ts * 1e9

video_df = pd.DataFrame(
    {
        "frames": np.arange(frames),
        "pts": [int(pt) for pt in pts],
        "timestamp [ns]": ts,
    }
)

merged_video = pd.merge_asof(
    video_df,
    gaze_df,
    on="timestamp [ns]",
    direction="nearest",
    suffixes=["video", "gaze"],
)


file_saving_path = Path(os.path.join(input_path, "merged_video.csv"))
merged_video.to_csv(file_saving_path, index=False)

