#include "vendor.h"
#include "vendor_global.h"
#include <cstdio>
#include <event.h>

#include <fstream>
#include <functional>
#include <getopt.h>
#include <iostream>
#include <memory>
#include <mutex>
#include <signal.h>
#include <sstream>
#include <string>
#include <sys/stat.h>
#include <sys/time.h>
#include <thread>
#include <unistd.h>
#include <utils/logger.h>
#include <vector>

static vendor::MyOpt myOpts_[] = {
    {"help", no_argument, 'h', "帮助"}
};
extern void signal_receive(int fd, short event, void *arg);
extern void signal_handle(int signal);

Vendor::Vendor()
{
    HTELINK_LOG_ENABLE(true);
    eventBase_ = event_base_new();
    if (eventBase_ == nullptr) {
        HTELINK_LOG_ERR("event new failed, %s");
    }
}

Vendor::~Vendor()
{
    char dumpFile[VENDOR_MAX_PATH_SIZE];
    sprintf("%s/log/event_stat_%s.txt", getenv(VENDOR_RUN_PATH_ENV), utils::nowtostr().c_str());
    FILE *fp = fopen(dumpFile, "a");
    event_base_dump_events(eventBase_, fp);
    fclose(fp);

    event_base_free(eventBase_);
}

int Vendor::ParseCmdline(const std::string &optname, const std::string &optarg)
{
    return 0;
}

vendor::MyOpt *Vendor::GetOpts()
{
    return myOpts_;
}

int Vendor::GetOptSize()
{
    return sizeof(myOpts_) / sizeof(myOpts_[0]);
}

int Vendor::Run()
{
    // 注册信号事件
    event_add(evsignal_new(eventBase_, SIGSEGV, signal_receive, NULL), NULL);
    event_add(evsignal_new(eventBase_, SIGFPE, signal_receive, NULL), NULL);
    event_add(evsignal_new(eventBase_, SIGINT, signal_receive, NULL), NULL);

    // 其他业务
    return event_base_dispatch(eventBase_);
}

void signal_receive(int fd, short event, void *arg)
{
    if (event != EV_SIGNAL) {
        HTELINK_LOG_ERR("fd: %d, event: %d occur", fd, event);
        return;
    }
    vendor::VendorBase::signal_handle(fd);
}
