/* Copyright 2022 Jaakko Keränen <jaakko.keranen@iki.fi>

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */

#include "SDL_timer.h"

#include <the_Foundation/sortedarray.h>
#include <the_Foundation/time.h>
#include <the_Foundation/thread.h>
#include <the_Foundation/mutex.h>

static iTime started_;

iDeclareType(Timer)
iDeclareType(PendingTrigger)
    
struct Impl_PendingTrigger {
    SDL_TimerID id;
    uint32_t    when;
    uint32_t    interval;
    void       *param;
    uint32_t  (*callback)(uint32_t, void *);
};

static int cmp_PendingTrigger_(const iPendingTrigger *a, const iPendingTrigger *b) {
    return iCmp(a->when, b->when);
}

struct Impl_Timer {
    SDL_TimerID  idEnum;
    iThread     *thread;
    iMutex       mtx;
    iCondition   waiting;
    iBool        isStopping;
    iSortedArray triggers;
};

static iThreadResult run_Timer_(iThread *thread) {
    iTimer *d = userData_Object(thread);
    iTime timeout;
    lock_Mutex(&d->mtx);
    initTimeout_Time(&timeout, 1.0);
    signal_Condition(&d->waiting);
    while (!d->isStopping) {
//        printf("waiting until %f\n", seconds_Time(&timeout));
        waitTimeout_Condition(&d->waiting, &d->mtx, &timeout);
        initTimeout_Time(&timeout, 60.0);
        if (d->isStopping) {
            break;
        }
        const uint32_t now = SDL_GetTicks();
        while (!isEmpty_SortedArray(&d->triggers)) {
            iPendingTrigger trig = *(iPendingTrigger *) front_Array(&d->triggers.values);
            if (trig.when > now) {
                /* Achieve better accuracy by ensuring we won't oversleep. */
                initTimeout_Time(&timeout, iMax(0.001, (trig.when - now) / 1000.0 * 0.75));
                break;
            }
            popFront_Array(&d->triggers.values);
            unlock_Mutex(&d->mtx);
            const uint32_t nextInterval = trig.callback(trig.interval, trig.param);
            lock_Mutex(&d->mtx);
            if (nextInterval) {
                trig.interval = nextInterval;
                trig.when += trig.interval;
                insert_SortedArray(&d->triggers, &trig);
            }
        }        
    }
    unlock_Mutex(&d->mtx);
    return 0;
}

static void init_Timer(iTimer *d) {
    d->isStopping = iFalse;
    d->idEnum = 0;
    init_Mutex(&d->mtx);
    init_Condition(&d->waiting);
    init_SortedArray(&d->triggers, sizeof(iPendingTrigger),
                     (iSortedArrayCompareElemFunc) cmp_PendingTrigger_);
    d->thread = new_Thread(run_Timer_);
    setUserData_Object(d->thread, d);
    start_Thread(d->thread);
}

static void deinit_Timer(iTimer *d) {
    d->isStopping = iTrue;
    signalAll_Condition(&d->waiting);
    join_Thread(d->thread);
    iRelease(d->thread);
    deinit_Condition(&d->waiting);
    deinit_Mutex(&d->mtx);
    deinit_SortedArray(&d->triggers);
}

iDefineTypeConstruction(Timer)

static iTimer *timer_;

/*----------------------------------------------------------------------------------------------*/

void SDL_InitTimer(void) {
    timer_ = new_Timer();
    initCurrent_Time(&started_);    
}

void SDL_QuitTimer(void) {
    delete_Timer(timer_);
    timer_ = NULL;
}

uint32_t SDL_GetTicks(void) {
    return (uint32_t) (elapsedSeconds_Time(&started_) * 1000);
}

uint64_t SDL_GetPerformanceFrequency(void) {
    return 1000000;
}

uint64_t SDL_GetPerformanceCounter(void) {
    const double elapsed = elapsedSeconds_Time(&started_);
    return (uint64_t) (elapsed * SDL_GetPerformanceFrequency());
}

void SDL_Delay(uint32_t milliseconds) {
    sleep_Thread(milliseconds / 1000.0);
}

SDL_TimerID SDL_AddTimer(uint32_t interval, uint32_t (*callback)(uint32_t, void *), void *param) {
    iTimer *d = timer_;
    iPendingTrigger trig = { .id       = ++d->idEnum,
                             .interval = interval,
                             .param    = param,
                             .when     = SDL_GetTicks() + interval,
                             .callback = callback };
    lock_Mutex(&d->mtx);
    insert_SortedArray(&d->triggers, &trig);
    signal_Condition(&d->waiting);
    unlock_Mutex(&d->mtx);
    return trig.id;
}

void SDL_RemoveTimer(SDL_TimerID id) {
    iTimer *d = timer_;
    lock_Mutex(&d->mtx);
    iForEach(Array, i, &d->triggers.values) {
        iPendingTrigger *trig = i.value;
        if (trig->id == id) {
            remove_ArrayIterator(&i);
        }
    }
    signal_Condition(&d->waiting);
    unlock_Mutex(&d->mtx);
}
