/**
 * Copyright (C) 2020 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#define _GNU_SOURCE
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include "../includes/memutils_track.h"
#include "eas.h"

char enable_selective_overload = ENABLE_NONE;

bool is_tracking_required(size_t size) {
    return ((size != 1024) && (size != 4096));
}

int EAS_fread(void *handle, void *buf, int offset, int size) {
    fseek(handle, offset, SEEK_SET);
    return fread(buf, 1, size, handle);
}

int EAS_fsize(void *handle) {
    fseek(handle, 0, SEEK_END);
    return ftell(handle);
}

static void PlayFile(EAS_DATA_HANDLE easData, const char* filename) {
    EAS_HANDLE handle;
    EAS_FILE file;
    file.handle = (void*) fopen(filename, "rb");
    file.readAt = EAS_fread;
    file.size = EAS_fsize;
    enable_selective_overload = ENABLE_MALLOC_CHECK;
    if (EAS_OpenFile(easData, &file, &handle) != EAS_SUCCESS) {
        enable_selective_overload = ENABLE_NONE;
        if(file.handle) {
            fclose(file.handle);
        }
        return;
    }
    EAS_Prepare(easData, handle);
    EAS_CloseFile(easData, handle);
    enable_selective_overload = ENABLE_NONE;
    if(file.handle) {
        fclose(file.handle);
    }
    return;
}

int main(int argc, char **argv) {
    EAS_DATA_HANDLE easData;
    EAS_RESULT result;

    if (argc < 2) {
        return EXIT_FAILURE;
    }

    result = EAS_Init(&easData);
    if (result != EAS_SUCCESS) {
        return EXIT_FAILURE;
    }
    PlayFile(easData, argv[1]);
    EAS_Shutdown(easData);
    return EXIT_SUCCESS;
}
