#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include <stdbool.h>
#include <unistd.h>
#include <termios.h>
#include <limits.h>
#include <time.h>
#include <pthread.h>
#include <stdatomic.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>

#include "structure.h"
#include "base.h"
#include "music.h"

static pthread_t threads[32];
static bool threadIsFree[32];
static int threadID;

static int thrID;

pthread_mutex_t lock;

void init_music() {
    pthread_mutex_init(&lock, NULL);
    threadID = 0;
    for(int k = 0; k < 32; k++) {
        threadIsFree[k] = true;
    }
}

void end_music() {
    pthread_mutex_destroy(&lock);

    FILE* endptr = fopen("sound/sem.txt", "w");
    fprintf(endptr, "0");
    fclose(endptr);

    usleep(100000);

    FILE* stptr = fopen("sound/sem.txt", "w");
    fprintf(stptr, "1");
    fclose(stptr);

    for(int k = 0; k < 32; k++) {
        if(!threadIsFree[k]) {
            printf("[pthread] killing %d\n", k);
            pthread_cancel(threads[k]);
        }
    }
}

void reset_music() {
    FILE* endptr = fopen("sound/sem.txt", "w");
    fprintf(endptr, "0");
    fclose(endptr);

    usleep(100000);

    FILE* stptr = fopen("sound/sem.txt", "w");
    fprintf(stptr, "1");
    fclose(stptr);
}

char* get_name(char* filename) {
    char* res = malloc(sizeof(char)*100);
    res[0] = '.';
    res[1] = '/';
    res[2] = 's';
    res[3] = 'o';
    res[4] = 'u';
    res[5] = 'n';
    res[6] = 'd';
    res[7] = '/';
    res[8] = 'm';
    res[9] = 'u';
    res[10] = 's';
    res[11] = 'i';
    res[12] = 'c';
    res[13] = ' ';
    int k = 14;
    while(k < 99 &&filename[k-14] != '\0') {
        res[k] = filename[k-14];
        k += 1;
    }
    res[k] = '\0';
    return res;
}

void* mainMusic(void* arg) {
    int localThreadID = thrID;
    char* name = get_name((char*)arg);
    int i=0;
    //while(name[i] != '\0') {
    //    printf("%c", name[i]);
    //    i +=1;
    //}
    system(name);
    free(name);
    threadIsFree[localThreadID] = true;
    //printf("thread %d is done\n", localThreadID);
    return NULL;
}

bool get_id(int* res) {
    int lp = 0;
    while(lp < 32) {
        if(threadIsFree[(lp+threadID)%32]) {
            *res = (lp+threadID)%32;
            return true;
        }
        lp += 1;
    }
    return false;
}

void play_sound(char* filename) {
    return;
    pthread_mutex_lock(&lock);
    int id;
    if(get_id(&id)) {
        //printf("[music] %d\n");
        threadIsFree[id] = false;
        thrID = id;
        threadID += 1;
        pthread_create(&threads[id], NULL, mainMusic, filename);
    } else {
        fprintf(stderr, "WARNING : cannot play audio %s (out of space)\n", filename);
    }
    pthread_mutex_unlock(&lock);
}