import ws from 'k6/ws';
import { check, sleep } from 'k6';
import stomp from 'k6/x/stomp';
import {SharedArray} from 'k6/data';

const users = new SharedArray('users', function() {
    return [{"sabun":"17131427","name":"권태현","talkId":"0a9cd322767b40069dbd7f5fe5b69401","workid":"HA0001","worknm":"SD요원 처리"}]
})


const currentDate = (idx) => {
    const date = new Date();

    // 날짜를 원하는 형식으로 포맷팅
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');  // 월은 0부터 시작하므로 +1
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    const milliseconds = Number(String(date.getMilliseconds()).padEnd(6, '0')) + idx;

    const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${milliseconds}`;
    return formattedDate;
}


export const options = {
    // vus: 2033,
    // Iterations: 2033,
    stages: [
        { duration: '30s', target: 200 },   // 1     500
        { duration: '1m', target: 400 },  // 2     1000
        { duration: '1m', target: 600 },  // 2     1000
        { duration: '2m', target: 1000 },  // 2     1000
        { duration: '3m', target: 2033 },  // 2     1000
        { duration: '1m', target: 1000 },  // 2     1000
        { duration: '1m', target: 500 },  // 2     1000
        { duration: '30s', target: 0 },     // 1     0
    ]
};

const WEBSOCKET_URL = "http://devtalk.kospo.co.kr:3000/stomp/talk"
const ROOM_DESTINATION = "/exchange/talk.exchange/room."
const MESSAGE_DESTINATION = "/queue/talk.queue"

export default function () {

    const userIndex = __VU % users.length;
    const user = users[userIndex];


    // connect to broker
    // const stompClient = stomp.connect({
    //     protocol: 'tcp',
    //     addr: 'localhost:61613',
    //     timeout: '15s',
    //     tls: false,
    //     user: 'talk',
    //     pass: 'kospo2024!',
    //     heartbeat: {
    //         incoming: '20s',
    //         outgoing: '20s',
    //     },
    //     host: '/',
    //     verbose: true,
    //     read_buffer_size: 4096,
    //     read_channel_capacity: 20,
    //     write_buffer_size: 4096,
    //     write_channel_capacity: 20,
    // });

    const stompClient = stomp.connect({
        protocol: 'tcp',
        addr: 'http://devtalk.kospo.co.kr:3000/stomp/talk',
        timeout: '15s',
        tls: false,
        heartbeat: {
            incoming: '20s',
            outgoing: '20s',
        },
        host: '/',
        verbose: true,
        read_buffer_size: 4096,
        read_channel_capacity: 20,
        write_buffer_size: 4096,
        write_channel_capacity: 20,
    })

    try {
        const subscribeOpts = {
            ack: 'client' // client-individual or auto (default)
        }


        const roomSub = stompClient.subscribe(`${ROOM_DESTINATION}${user.talkId}`, subscribeOpts);

        const insDate = currentDate(__VU).padEnd(26, '0');
        const messageParam = {
            type: "MESSAGE",
            insSabun: user.sabun,
            insName : user.name,
            insDate : insDate,
            message: '',
            talkId: user.room,
            workId: user.workId,
            workNm: user.workNm,
            introOwner:  '',
            talkAttachDtos: [],
            attach: null,
        }


        messageParam.message = `부하 테스트 ${user.name} ${user.room}`
        stompClient.send(`${MESSAGE_DESTINATION}`, 'application/json', JSON.stringify(messageParam))


        // setTimeout(stompClient.unsubscribe, 240000)
        sleep(10)
    } catch(e) {
        console.error(e);
    }
}

export function setup() {
    console.log("text setup completed with users : ", users.length)
    return {userCount: users.length}
}

export function teardown(data) {
    // disconnect from broker
    console.log('test completed total users tested : ', data.userCount)
}