/*
     Description: 排序过程的第二阶段

     Copyright : All right reserved by ICT

     Author : Zhang Zhonghai
     Date : 2026/02/08
*/

#include "phase_2.h"

#include <klib/kthread.h>
#include <spdlog/spdlog.h>

#include "common_data.h"
#include "phase_2_read.h"
#include "phase_2_merge.h"
#include "phase_2_write.h"
#include "util/profiling.h"

uint64_t block_id = 0;
uint64_t read_bam_id = 0;
uint64_t copy_bam_id = 0;
uint64_t write_bam_id = 0;

void phase2Pipeline(Phase2PipelineArg& p) {
    PROF_G_BEG(phase2);
    /* create threads */
    pthread_t tidArr[6];  // 2-stage pipeline
    pthread_create(&tidArr[0], NULL, phase2ReadMidFile, &p);
    pthread_create(&tidArr[1], NULL, phase2Uncompress, &p);
    pthread_create(&tidArr[2], NULL, phase2CopyToMergeBuf, &p);
    pthread_create(&tidArr[3], NULL, phase2Merge, &p);
    pthread_create(&tidArr[4], NULL, phase2Compress, &p);
    pthread_create(&tidArr[5], NULL, phase2Write, &p);

    for (int i = 0; i < 6; ++i) pthread_join(tidArr[i], NULL);
    //for (int i = 0; i < 4; ++i) pthread_join(tidArr[i], NULL);

    spdlog::info("all bams num: {}", p.numBam);

    PROF_G_END(phase2);
}