/// <reference path="../../exports/exports.d.ts" />
console.log("HELLO WORLD");
module.paths.push("../../build/linux_x64");
module.paths.push("../../build/win32_64");

//LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libasan.so.5
const os = require('os');
//process.dlopen(module, '/usr/lib/x86_64-linux-gnu/libasan.so.5',
//    os.constants.dlopen.RTLD_NOW);
import * as fs from "fs";

const original_require = require;
require = (module => original_require("/home/wolverindev/TeaSpeak-Client/client/native/build/linux_x64/" + module + ".node")) as any;
import * as handle from "teaclient_connection";
require = original_require;

const connection_list = [];
const connection = handle.spawn_server_connection();
const client_list = [];

console.dir(handle);
console.log("Query devices...");
console.log("Devices: %o", handle.audio.available_devices());
console.log("Current playback device: %o", handle.audio.playback.current_device());
//handle.audio.playback.set_device(14);
//console.log("Current playback device: %o", handle.audio.playback.current_device());

const stream = handle.audio.playback.create_stream();
console.log("Own stream: %o", stream);


/* -1 => default device */
const recorder = handle.audio.record.create_recorder();
console.log("Have device: %o", recorder);
console.log("Device: %o", recorder.get_device());
if(recorder.get_device() == -1) {
    console.log("Looking for devices");
    for(const device of handle.audio.available_devices()) {
        if(!device.input_supported)
            continue;
        if(device.name != "pulse")
            continue;
        console.log("Found pulse at %o", device.device_index);
        recorder.set_device(device.device_index, () => {});
    }
}
console.log("Device: %o", recorder.get_device());
recorder.start(() => {});
console.log("Started: %o", recorder.started());

const consumer = recorder.create_consumer();

{
    const filter = consumer.create_filter_threshold(.5);
    filter.set_margin_frames(10);
    /*
    filter.set_analyze_filter(value => {
        console.log(value);
    })
    */
}

{
    //const filter = consumer.create_filter_vad(3);
    //console.log("Filter name: %s; Filter level: %d; Filter margin: %d", filter.get_name(), filter.get_level(), filter.get_margin_frames());
}

{
    const consume = consumer.create_filter_state();
    setTimeout(() => {
        console.log("Silence now!");
        consume.set_consuming(true);

        setTimeout(() => {
            console.log("Speak now!");
            consume.set_consuming(false);
        }, 1000);
    }, 1000);
}



//process.exit(0);
connection.callback_command = (command, args, switches) => {
    //console.log("Got command %s: %o (%o)", command, args, switches);
    if(command === "notifycliententerview") {
        for(const client_args of args) {
            console.log(client_args["clid"]);
            const client = connection._voice_connection.register_client(parseInt(client_args["clid"]));
            console.log("Registered voice client %o", client);
            client_list.push(client);

            console.log("Applying volume of 0.2");
            client.set_volume(0.2);

            const stream = client.get_stream();
            console.log("Client buffer latency: %d/%d: %o", stream.get_buffer_latency(), stream.get_buffer_max_latency(), stream);
            stream.set_buffer_latency(0.02);
            stream.set_buffer_max_latency(0.2);

            client.callback_playback = () => {
                console.log("Client %d started speaking", client.client_id);
            };

            client.callback_stopped = () => {
                console.log("Client %d stopped speaking", client.client_id);
            };

            client.callback_state_changed = state => {
                console.log("Client %d change state to %d (%s)", client.client_id, state, handle.PlayerState[state]);
            };

        }
    }
};

connection.callback_disconnect = reason => {
    console.log("Got disconnect: %s", reason);
};

const do_connect = () => {
    connection.connect({
        timeout: 5000,
        remote_port: 9987,
        //remote_host: "188.40.240.20", /* twerion */
        //remote_host: "localhost",
        remote_host: "ts.teaspeak.de",
        //remote_host: "51.68.181.92",
        //remote_host: "94.130.236.135",
        //remote_host: "54.36.232.11", /* the beast */
        //remote_host: "79.133.54.207", /* gommehd.net */
        callback: error => {
            console.log("Connected with state: %o (%s) ", error, connection.error_message(error));

            if(error == 0) {
                console.dir(handle.ServerType);
                console.log("Server type: %o|%o", connection.server_type, handle.ServerType[connection.server_type]);
                connection.send_command("clientinit", [
                    {
                        "client_key_offset": 2030434,
                        /*
                        "client_version": "1.0.0",
                        "client_platform": "nodejs/linux",
                        */
                        "client_version": "3.1.8 [Build: 1516614607]",
                        "client_platform": "Windows",
                        "client_version_sign": "gDEgQf/BiOQZdAheKccM1XWcMUj2OUQqt75oFuvF2c0MQMXyv88cZQdUuckKbcBRp7RpmLInto4PIgd7mPO7BQ==",

                        "client_nickname": "TeaClient Native Module Test",

                        "client_input_hardware":true,
                        "client_output_hardware":true,
                        "client_default_channel":"",
                        "client_default_channel_password":"",
                        "client_server_password":"",
                        "client_meta_data":"",
                        "client_nickname_phonetic":"",
                        "client_default_token":"",
                        "hwid":"123,456123123123",
                        return_code:91
                    }
                ], []);

                consumer.callback_ended = () => {
                    console.log(">> Audio end");
                };

                connection._voice_connection.set_audio_source(consumer);
                /*
                consumer.callback_data = buffer => {
                    console.log("Sending voice data");
                    connection.send_voice_data_raw(buffer, consumer.channels, consumer.sample_rate, true);
                    //stream.write_data_rated(buffer.buffer, true, consumer.sample_rate);
                };
                 */
            }
        },

        identity_key: "MG4DAgeAAgEgAiBC9JsqB1am6vowj2obomMyxm1GLk8qyRoxpBkAdiVYxwIgWksaSk7eyVQovZwPZBuiYHARz/xQD5zBUBK6e63V7hICIQCZ2glHe3kV62iIRKpkV2lzZGZtfBPRMbwIcU9aE1EVsg==",
        teamspeak: true /* used here to speed up the handsahke process :) */
    });

    connection.callback_voice_data = (buffer, client_id, codec_id, flag_head, packet_id) => {
        console.log("Having data!");
        connection.send_voice_data(buffer, codec_id, flag_head);
    };

    connection.callback_command = (command, arguments1, switches) => {
        console.log("Command: %s", command);
    }

    connection._voice_connection.register_client(7);
};
do_connect();

connection.callback_voice_data = (buffer, client_id, codec_id, flag_head, packet_id) => {
    console.log("Received voice of length %d from client %d in codec %d (Head: %o | ID: %d)", buffer.byteLength, client_id, codec_id, flag_head, packet_id);
    connection.send_voice_data(buffer, codec_id, flag_head);
};

setInterval(() => {
    console.log("GC");
    global.gc();
}, 1000);

let a_map = [consumer, recorder];
/* keep the object alive */
setTimeout(() => {
    connection.connected();
    a_map = a_map.filter(e => true);
}, 1000);

connection_list.push(connection);