/***************************************************************************/
/*                             Druckersoftware                             */
/*                    Copyright (C) Carl Valentin GmbH                     */
/***************************************************************************/

/*
 * JobApi.h
 *
 *  Created on: 08.04.2022
 *      Author: preitinger
 */

#ifndef JOBAPI_H_
#define JOBAPI_H_

/**** DEPRECATED!!! Samt alten KM devices abgeloest durch jobapi/KM_JobApi.h & Co ****/

#include <linux/completion.h>
#include <linux/mutex.h>

#include "fpgaSerial/dmaPayloadKM.h"
#include "fpgaSerial/fpgaCommands.h"

typedef enum EJobApiState {
    CV_API_DOWN,
    CV_API_UP,
} JobApiState;

static JobApiState cvApiSt = CV_API_DOWN;
static DEFINE_MUTEX(cvApiMutex);

void JobApi_up(void) {
    mutex_lock(&cvApiMutex);
    cvApiSt = CV_API_UP;
    mutex_unlock(&cvApiMutex);
}

void JobApi_closeDmaCb(void* arg) {
    struct completion* compl = arg;

    pr_info("JobApi_closeDmaCb\n");
    complete_all(compl);
}

static void _JobApi_sendAndJoinCloseJobApiDma(void) {
    DECLARE_COMPLETION_ONSTACK(compl);

    fpgaSendCmdWithResp(create_closeJobApiDma(), JobApi_closeDmaCb, &compl);
    pr_info("closeJobApiDma sent\n");
    wait_for_completion(&compl);
    pr_info("done for closeJobApiDma received\n");
}

void JobApi_down(void) {
    pr_info("JobApi_down\n");
    mutex_lock(&cvApiMutex);

    switch (cvApiSt) {
        case CV_API_DOWN:
            break;

        case CV_API_UP:
            _JobApi_sendAndJoinCloseJobApiDma();
            cvApiSt = CV_API_DOWN;
            break;

        default:
            ASSERT(false);
    }

    mutex_unlock(&cvApiMutex);
}
void JobApi_handleCrash(void) {
    // check job api state and if active, make the fpga stop any jobapi dma transfers
    JobApi_down();
}

#endif /* JOBAPI_H_ */
