#include "mysignal.h"
#include "pthread.h"
#include "stdlib.h"
#include "lambda.h"
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/types.h>
#include "stdio.h"
#include "errno.h"
#include <semaphore.h>
#include "exception.h"
#include "mythread.h"
#include "debug.h"


static int _thread(void* arg) {
  mythread_t* self = arg;
  slot_list_with_pars *slot_p;
  while (1) {
    slot_p = NULL;
    sem_wait(&self->sem);
    pthread_mutex_lock(&self->lock);
    DBG_INFO("sem take\n");
    // 把槽列表里的函数取出来
    if (self->slot_head) {
      slot_p = self->slot_head;
      self->slot_head = self->slot_head->next;
    }
    pthread_mutex_unlock(&self->lock);
    if (slot_p) {
      if (slot_p->func) {
        DBG_INFO("args_p=%p\n", slot_p);
        slot_p->func(slot_p);
      }
      // 槽函数执行完之后释放
      free(slot_p);
    }
  }
  return 0;
}


// 添加异步执行的槽函数
void send_slot_fun(mythread_t *self, slot_list_with_pars* slot_p) {
  // 这里根据tid来决定把槽函数添加到哪个线程的槽列表里
  pthread_mutex_lock(&self->lock);
  if (self->slot_head == NULL) {
    self->slot_head = slot_p;
  } else {
    // 添加到槽列表的开头
    slot_p->next = self->slot_head;
    self->slot_head = slot_p;
  }
  pthread_mutex_unlock(&self->lock);
  sem_post(&self->sem);
  DBG_INFO("add_slot_fun\n");
}


void _connect(void* sig_obj, void* sig_fun, mythread_t* thread, void* slot_obj, const char* slot_fun) {
  __SIG_OBJ* sig_p = (__SIG_OBJ*)sig_obj;
  slot_list* slot_p = calloc(sizeof(slot_list), 1);
  slot_p->slot_obj = slot_obj;
  slot_p->func = signal_find_slot_func(slot_fun);
  slot_p->signal_func = sig_fun;
  if (!slot_p->func) {
    // 找不到槽函数，无法连接
    free(slot_p);
    return;
  }
  slot_p->thread = thread;
  if (sig_p->slot_head == NULL) {
    sig_p->slot_head = slot_p;
  } else {
    slot_p->next = sig_p->slot_head;
    sig_p->slot_head = slot_p;
  }


}


mythread_t *sigthread_init(const char *name) {
  mythread_t* self = calloc(1, sizeof(mythread_t));
  pthread_mutex_init(&self->lock, NULL);
  sem_init(&self->sem, 0, 0);
  // pthread_create(&self->tid, NULL, _thread, self);
  self->tid = myth_create(_thread, self, name);
  return self;
}


__attribute__((weak)) void* signal_find_slot_func(const char* name) {
  return 0;
}
