<?php

include('config.php');
include("db_mediaq.php");
include("Util.php");

if (!DEBUGGING_MODE){
    header('Content-Type: application/json');
}
if (isset ($_POST['username'])) {
    $username = $_POST ['username'];
    performQuery($username);
}

/**
 * @param $username
 */
function performQuery($username)
{
    // Zeitmessung
    $date = new DateTime();
    $startTime = $date->getTimestamp();

    $allmyvideos = getMyVideoIds($username);
    $result_arr = array();

    foreach ($allmyvideos as $myvideoid) {
        // get my actual video-sub-entries
        $myvideo_meta_entries = getVideoMetaEntries($myvideoid);

        foreach ($myvideo_meta_entries as $myvideo_single_entry) {

            // get video-sub-entrys candidates which could intersect my actual video-segment (TEMPORAL COMPARE (-1second, +1second)
            $temporal_intersection_videos = getVideosWhichCouldIntersectWithMyVideo($myvideoid, $myvideo_single_entry[TIMESTAMP] - 10000, $myvideo_single_entry[TIMESTAMP] + 10000);

            foreach ($temporal_intersection_videos as $temporal_intersection_candidate) {
                performPointIntersectsViewingAreaCheck($temporal_intersection_candidate, $myvideo_single_entry, $result_arr);
            }
        }

    }

    $indexedOnly = array();

    $i = 0;
    foreach ($result_arr as $value) {
        $startTimeVideo = getVideoStartTime($value["value"]);
        $value["mintimespan"] = $value["mintimespan"] - $startTimeVideo;
        $value["maxtimespan"] = $value["maxtimespan"] - $startTimeVideo;
        $indexedOnly[$i] = $value;
        $i++;
    }

    closeSqlConnection();

    $date = new DateTime();
    $endTime = $date->getTimestamp();
    $return_arr = ['starttime' => $startTime, 'endtime' => $endTime, 'result' => $indexedOnly];

    //return $return_arr;
    if (DEBUGGING_MODE){
        return $return_arr;
    }else {
        echo json_encode($return_arr);
    }
}


