var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
import init, { encrypt_or_decrypt_files2, password, sanitize_base64, base64_to_vec, vec_to_base64, uuid_generate, encode_base64 } from 'my-crate';
import './style.css';
import $ from 'jquery';
import iro from '@jaames/iro';
import Plyr from 'plyr';
import { Polybase } from "@polybase/client";
// import { Mp3Recorder } from './Mp3Recorder.mjs';
import Recorder from "yiyi-audio-recorder";
import { uniqueNamesGenerator, adjectives, colors, animals } from 'unique-names-generator';
// const v = "lassis";
// import { password } from '../my-crate/pkg/my_crate';
// wasm-pack build ./my-crate --target web
// https://rustwasm.github.io/wasm-pack/installer/
// const db = new Polybase({
//   defaultNamespace: "data_space",
// });
var db = new Polybase({
    defaultNamespace: "data_space",
    signer: function (data) {
        // Enter your condition to skip the signing process. 
        return null;
    }
});
var collectionReference = db.collection("cid");
var decoder = new TextDecoder();
var uploadedFiles = [];
var colorPicker = iro.ColorPicker("#picker", {
    width: 120,
    color: "#6842ff",
    borderWidth: 5,
    borderColor: "#ffffff",
    layout: [
        {
            component: iro.ui.Wheel,
            options: {}
        },
    ]
});
$("#algo_button_box").hide();
$("#container_algorand").hide();
//===================================================================== 
// BUTTONS LAYER
//===================================================================== 
$("#love_matchings").on('click', function () {
    $("#love_matchings").addClass("animated");
    // Open the new window after the transition or animation has completed
    setTimeout(function () {
        window.open("https://love.farfallasocial.repl.co/", '_blank');
    }, 500);
});
$("#infinity_nomads").on('click', function () {
    $("#infinity_nomads").addClass("animated");
    // Open the new window after the transition or animation has completed
    setTimeout(function () {
        window.open("https://infinity.farfallasocial.repl.co/", '_blank');
    }, 500);
});
$("#info_pop").on('click', function () {
    if ($('#info_box').length == 0) {
        $('#anchor_info_pop').append("\n      <div id='info_box'>\n        <div id='title_steps'>Guidance</div>\n        <div class=\"line-break0\"></div>\n        <div class='first_step'>If you require a translator, we enjoy using this <a href=\"https://www.deepl.com/translator\" target=\"_blank\">Deep Learning model</a>.</div>\n        <div class=\"line-break0\"></div>\n        <div class='first_step'>If you require a place to store your notes securely and privaely, we enjoy using this <a href=\"https://www.protectedtext.com/\" target=\"_blank\">notepad</a>.</div>\n        <div class=\"line-break0\"></div>\n        <div class='first_step'>PhiliaSocial Chat uses Aes256Gcm; for further reading visit this <a href=\"https://crates.io/crates/aes-gcm\" target=\"_blank\">Rust crate.</a></div>\n        <div class=\"line-break0\"></div>\n        <div class='first_step'>The locally encrypted messages and files are uploaded to the <a href=\"https://www.arweave.org/\" target=\"_blank\">Arweave network</a> using the <a href=\"https://bundlr.network/\" target=\"_blank\">Bundlr Network</a>. The CIDs of your data are then stored on <a href=\"https://polybase.xyz/\" target=\"_blank\">Polybase</a>, within Polybase, the CIDs are stored under a single \"collection\"; this adds a \"lost in the crowd\" complexity to the message route. Please be mindful that the encrypted files are not guaranteed to be available indefinitely due the beta nature of PhiliaSocial Chat.</div>\n        <div class=\"line-break0\"></div>\n        <div class='first_step'>On another note, use <a href=\"https://giphy.com/\" target=\"_blank\">Giphy</a> or <a href=\"https://tenor.com/\" target=\"_blank\">Tenor</a> to insert GIF-links into your Chat-space.</div>\n        <div class=\"line-break0\"></div>\n        <div class='first_step'>Contact us: connect at philia dot social</div>\n      </div>\n        ");
    }
    ;
});
$("#anchor_info_pop").on('click', function () {
    if ($('#info_box').length) {
        $('#info_box').remove();
    }
});
$("#note_pad").on('click', function () {
    $("#note_pad").addClass("animated");
    // Open the new window after the transition or animation has completed
    setTimeout(function () {
        window.open("https://cryptgeon.org/", '_blank');
    }, 500);
});
$("#show_hide_password").on('click', function () {
    var check_val = $('.fa-eye').length;
    switch (check_val) {
        case 1:
            $(".survey-options").attr("type", "text");
            $("#fa_eye")
                .removeClass("fa-solid fa-eye")
                .addClass("fa-solid fa-eye-slash");
            break;
        default:
            $(".survey-options").attr("type", "password");
            $("#fa_eye")
                .removeClass("fa-solid fa-eye-slash")
                .addClass("fa-solid fa-eye");
            break;
    }
});
init().then(function () {
    setTimeout(function () {
        $(".container_intro").fadeOut(2000);
        $("#algo_button_box").show();
    }, 2000);
    function public_key_step() {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                $('#ft_expanded_2').append("\n    <div id=\"spacing_second\" class=\"line-break0\"></div>\n    <div id=\"second_orig\" class=\"peer_orig_inputs\">Click the Copy button above to copy the complete Chat-Credentials below, then navigate to Cryptgeon and create a note with them; share the generated link with your partner(s).</div>\n      <div id=\"survey_pub_key2\" class=\"survey_options_algo2\">\n        <input id=\"association_algo_password\" type=\"password\" name=\"survey_options_name\" class=\"survey-options\"/>\n      </div>\n    ");
                return [2 /*return*/];
            });
        });
    }
    $("#input_label_button_pub_key").on('click', function () {
        // $("#input_label_button_farfalla_key").hide();
        // $("#input_label_button_contact_key").hide();
        // $("#original_space").hide();
        $("#first_task").hide();
        var condition_ft = $("#input_label_button_pub_key").html() === "Create New Credentials";
        var expandedContent = document.getElementById('ft_expanded_2');
        if (condition_ft == true) {
            $("#input_label_button_pub_key").text("Return Home");
            if (expandedContent.style.display === 'block') {
                expandedContent.style.display = 'none';
            }
            else {
                expandedContent.style.display = 'block';
                if ($("#association_algo_password").length == 0) {
                    public_key_step().then(function () {
                        // const new_public = generate_public_key();
                        // const new_chat = new_chat_id();
                        var new_chat = encode_base64(uuid_generate());
                        var new_public = password().replace(/=/g, '');
                        // console.log([new_chat.length, new_public.length])
                        var joined_credentials = new_chat + new_public;
                        // console.log(joined_credentials)
                        $("#association_algo_password").val("".concat(joined_credentials));
                    });
                }
                ;
            }
            ;
        }
        else {
            $("#input_label_button_pub_key").html("Create New Credentials");
            expandedContent.style.display = 'none';
            // $("#input_label_button_farfalla_key").show();
            // $("#input_label_button_contact_key").show();
            // $("#original_space").show();
            $("#first_task").show();
            $("#association_algo_password").remove();
            $("#association_algo_password0").remove();
            $(".survey_options_algo2").remove();
            $("#second_orig").remove();
            $("#spacing_second").remove();
            $("#soft_encrypted_credential").remove();
        }
        ;
    });
    function initial_text_area_view() {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if ($("#association_algo_password4").length == 0) {
                            $("#wrapper_username").append("\n      <div class=\"inputs_labels\">Add any optional metadata:</div>\n      <div id class=\"line-break0\"></div>\n      <div  class=\"survey_options_algo\">\n        <input id=\"association_algo_password4\" type=\"text\" name=\"survey_options_name4\" class=\"survey-options\" placeholder=\"Ex: 01 Mikasa A.\"/>\n      </div>\n      <div class=\"messages_labels\">\n        <div>Safe Qty.</div>\n        <div>Risky Qty.</div>\n      </div>\n      <div id=\"messages_count\"></div>\n      <div class=\"messages_labels\">\n        <div>0</div>\n        <div>Messages</div>\n        <div>500</div>\n      </div>\n      ");
                        }
                        ;
                        // try{
                        return [4 /*yield*/, loop_algorand()];
                    case 1:
                        // try{
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    }
    $(document).ready(function () {
        // Event listener for 'keydown' on input element with ID 'association_algo_password2'
        $('#association_algo_password2').on('keydown', function (event) {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!(event.key === 'Enter')) return [3 /*break*/, 2];
                            event.preventDefault(); // Prevent the default action of the Enter key
                            return [4 /*yield*/, processCredentials()];
                        case 1:
                            _a.sent();
                            _a.label = 2;
                        case 2: return [2 /*return*/];
                    }
                });
            });
        });
        // Event listener for 'click' on element with ID 'input_label_button_farfalla_key'
        $("#input_label_button_farfalla_key").on('click', function () {
            return __awaiter(this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 /*yield*/, processCredentials()];
                        case 1:
                            _a.sent();
                            return [2 /*return*/];
                    }
                });
            });
        });
        function processCredentials() {
            return __awaiter(this, void 0, void 0, function () {
                var assoc_pass2, credentials, split_credentials_chatId, split_credentials_private, error_1;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            assoc_pass2 = $("#association_algo_password2").val().toString().length;
                            if (!(assoc_pass2 == 91)) return [3 /*break*/, 4];
                            $("#input_label_button_pub_key").hide();
                            $("#input_label_button_contact_key").hide();
                            credentials = $("#association_algo_password2").val().toString().trim();
                            split_credentials_chatId = credentials.substring(0, 48);
                            split_credentials_private = credentials.substring(48, 91);
                            global_chat_space_key = split_credentials_chatId;
                            if (!(credentials.length == 91 && split_credentials_chatId.length == 48 && split_credentials_private.length == 43)) return [3 /*break*/, 4];
                            $('#algo_button_box').hide();
                            $('#algo_gate').hide();
                            $("#container_algorand").show();
                            chat_space_id = split_credentials_chatId;
                            chat_space_private = split_credentials_private;
                            $('#wallet_connected_chat').html("".concat(split_credentials_chatId));
                            $("#wallet_connected_chat").on('click', function () {
                                window.open("https://explorer.testnet.polybase.xyz/collections/data_space%2Fcid", '_blank');
                            });
                            _a.label = 1;
                        case 1:
                            _a.trys.push([1, 3, , 4]);
                            return [4 /*yield*/, initial_text_area_view()];
                        case 2:
                            _a.sent();
                            get_latest_note();
                            return [3 /*break*/, 4];
                        case 3:
                            error_1 = _a.sent();
                            return [3 /*break*/, 4];
                        case 4: return [2 /*return*/];
                    }
                });
            });
        }
    });
    //   function confirm_copied(){
    //     $(".fa-copy").remove();
    //     $("#copy_field").html(`Copied!`);
    //     setTimeout(() => {
    //       // $(".fa-clipboard-check").remove();
    //       $("#copy_field").html(`Copy`);
    //     }, 2000);
    //   }
    //   $("#copy_field").on('click', function(){
    //     const get_pub_key = $("#input_label_button_pub_key").html() === `Return Home`;
    //     // const get_contact_key = $("#input_label_button_contact_key").html() === `Before continuing, be sure to copy the Chat-Id and store it safely. Founder, share the Chat-Id with your Partner by creating and sharing a new Cryptgeon note. At this time both of you should have: each other's Public-Key; your Public-Key; your Private-Key; lastly, the Chat-Id. When you are ready to proceed, click this text.`;
    //     // const get_contact_key2 = $("#input_label_button_contact_key").html() === `To ensure the security of your Chat space please follow these steps: first, copy and store safely the Encrypted Credentials. Next, use Cryptgeon to generate a sharable link containing the Encrypted Credentials; share this link with your Partner. Remind your Partner to visit the farfalla@ web app to decrypt the Encrypted Credentials. Your Unencrypted and Decrypted Credentials are ready to be use to enter the Chat space you have created. When you are ready, click this text to refresh the web app.`;
    //     if(get_pub_key==true){
    //       navigator.clipboard.writeText(`${$("#association_algo_password").val()}
    // `);
    //       confirm_copied()
    //     } 
    //   });
    // Function to confirm that text has been copied
    function confirmCopied() {
        $(".fa-copy").remove();
        $("#copy_field").html("Copied!");
        setTimeout(function () {
            $("#copy_field").html("Copy");
        }, 2000);
    }
    // Function to handle the click event on the copy field
    function handleCopyFieldClick() {
        return __awaiter(this, void 0, void 0, function () {
            var isReturnHome, textToCopy, error_2;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        isReturnHome = $("#input_label_button_pub_key").html() === "Return Home";
                        if (!isReturnHome) return [3 /*break*/, 4];
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        textToCopy = $("#association_algo_password").val();
                        return [4 /*yield*/, navigator.clipboard.writeText(textToCopy)];
                    case 2:
                        _a.sent();
                        confirmCopied();
                        return [3 /*break*/, 4];
                    case 3:
                        error_2 = _a.sent();
                        console.error("Failed to copy text: ", error_2);
                        return [3 /*break*/, 4];
                    case 4: return [2 /*return*/];
                }
            });
        });
    }
    // Attach the click event listener
    $(document).ready(function () {
        $("#copy_field").on("click", handleCopyFieldClick);
    });
});
// const gf = new GiphyFetch('O2LqnkYYdR5ckdntfpOINQLjmsOX1OKH');
// $('#gif').on('click', async function () {
//   const response = await fetch(`https://api.giphy.com/v1/gifs/trending?api_key=${"O2LqnkYYdR5ckdntfpOINQLjmsOX1OKH"}&limit=10`);
//   const data = await response.json();
//   const gifs = data.data;
//   const mountNode = document.getElementById('container_algorand'); // Replace with the ID of the element where you want to render the GIFs
//   gifs.forEach((gif) => {
//     const img = document.createElement('img');
//     img.src = gif.images.original.url;
//     img.alt = gif.title;
//     mountNode.appendChild(img);
//   });
// });
$('#headset').on('click', function () {
    return __awaiter(this, void 0, void 0, function () {
        var newUUID, randomName, videoChatUrl;
        return __generator(this, function (_a) {
            newUUID = uuid_generate();
            randomName = uniqueNamesGenerator({ dictionaries: [adjectives, colors, animals] });
            videoChatUrl = "https://c2c.mirotalk.com/join?room=".concat(newUUID, "&name=").concat(randomName);
            window.open(videoChatUrl, '_blank');
            return [2 /*return*/];
        });
    });
});
var main_message = $("#messages");
colorPicker.on('color:change', function (color) {
    main_message.css('color', "".concat(color.hexString));
});
var uploadDiv = document.getElementById("add_file");
var input = document.getElementById("file-input");
input.addEventListener("change", handleUpload);
uploadDiv.addEventListener("click", function () { return input.click(); });
//// remove file name from the uploadedFiles array
$('#anchor_file_names').on('click touchend', function (event) {
    if ($(event.target).is('.file_name')) {
        var index = $(event.target).index();
        $(event.target).remove();
        uploadedFiles.splice(index, 1);
    }
});
// let chat_space_party_pk:string;
var chat_space_private;
var chat_space_id;
// encrypting files...
var Encryption = /** @class */ (function () {
    // public additional: string;
    function Encryption(private_k) {
        // this.public_k = public_k;
        this.private_k = private_k;
        // this.additional = additional;
    }
    Encryption.prototype.encrypt = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                // return encrypt_file(this.key, data);
                return [2 /*return*/, encrypt_or_decrypt_files2("encrypt", this.private_k, data)];
            });
        });
    };
    Encryption.prototype.decrypt = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, encrypt_or_decrypt_files2("decrypt", this.private_k, data)];
            });
        });
    };
    ;
    return Encryption;
}());
;
function encryptUploadedFile(coloring, file, labels) {
    return __awaiter(this, void 0, void 0, function () {
        var encryption, buffer, textEnc, uint8Array_col, uint8Array_lab, encryptedColoring, encryptedFile, encryptedLabels, colo_enc, file_enc, labels_enc, obj;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    $("#wrapper_message_tools1").hide();
                    $("#wrapper_message_tools2").hide();
                    $('#fs_button_loader_wrapper1').append("\n  <div class=\"chat_space\" id=\"a_message\">Working...</div>\n  ");
                    $("#fs_button_loader_wrapper1").show();
                    encryption = new Encryption(chat_space_private);
                    return [4 /*yield*/, new Response(file).arrayBuffer()];
                case 1:
                    buffer = _a.sent();
                    textEnc = new TextEncoder();
                    uint8Array_col = textEnc.encode(coloring);
                    uint8Array_lab = textEnc.encode(labels);
                    return [4 /*yield*/, encryption.encrypt(uint8Array_col)];
                case 2:
                    encryptedColoring = _a.sent();
                    return [4 /*yield*/, encryption.encrypt(new Uint8Array(buffer))];
                case 3:
                    encryptedFile = _a.sent();
                    return [4 /*yield*/, encryption.encrypt(uint8Array_lab)];
                case 4:
                    encryptedLabels = _a.sent();
                    colo_enc = vec_to_base64(encryptedColoring);
                    file_enc = vec_to_base64(encryptedFile);
                    labels_enc = vec_to_base64(encryptedLabels);
                    obj = { fh: colo_enc, fl: labels_enc, fd: file_enc };
                    uploadedFiles.push(obj);
                    $("#wrapper_message_tools1").show();
                    $("#wrapper_message_tools2").show();
                    $("#a_message").remove();
                    return [2 /*return*/];
            }
        });
    });
}
;
//Web-worker
var ipfs_links = [];
function composition_notes(links) {
    return __awaiter(this, void 0, void 0, function () {
        var error_3;
        var _this = this;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    _a.trys.push([0, 2, , 3]);
                    // Wait for all the outer promises to resolve
                    return [4 /*yield*/, Promise.all(links.map(function (note) { return __awaiter(_this, void 0, void 0, function () {
                            var innerPromises;
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0:
                                        innerPromises = note.map(function (x) {
                                            var arweave_obj_id = uuid_generate();
                                            fetch_data_links.push(x);
                                            fetch_data_links_ids.push(arweave_obj_id);
                                            // Chain the unlock_button() promise without using async/await within the map
                                            return unlock_button(arweave_obj_id);
                                        });
                                        // Wait for all the inner promises to resolve
                                        return [4 /*yield*/, Promise.all(innerPromises)];
                                    case 1:
                                        // Wait for all the inner promises to resolve
                                        _a.sent();
                                        return [2 /*return*/];
                                }
                            });
                        }); }))];
                case 1:
                    // Wait for all the outer promises to resolve
                    _a.sent();
                    return [3 /*break*/, 3];
                case 2:
                    error_3 = _a.sent();
                    return [3 /*break*/, 3];
                case 3: return [2 /*return*/];
            }
        });
    });
}
var processArrayNotes = function (notes) { return __awaiter(void 0, void 0, void 0, function () {
    var promises, results, elements, lastElement, error_4;
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0:
                // console.log(notes)
                cache.clear();
                // console.log("init")
                $("#wrapper_message_tools1").hide();
                $("#wrapper_message_tools2").hide();
                if ($('#a_message').length === 0) {
                    $('#fs_button_loader_wrapper1').append("\n      <div class=\"chat_space\" id=\"a_message\">Working...</div>\n    ");
                }
                _a.label = 1;
            case 1:
                _a.trys.push([1, 3, 4, 5]);
                promises = notes.map(function (note, index) {
                    // console.log(note)
                    return fetchEncryptedFileMemoized(note, index);
                });
                return [4 /*yield*/, Promise.all(promises)];
            case 2:
                results = _a.sent();
                // console.log(results)
                results.sort(function (a, b) { return a.index - b.index; });
                ipfs_links = results.map(function (res) { return res.result; });
                $("#wrapper_message_tools1").show();
                $("#wrapper_message_tools2").show();
                $("#a_message").remove();
                composition_notes(ipfs_links);
                elements = document.querySelectorAll('.separator');
                lastElement = elements[elements.length - 1];
                lastElement.scrollIntoView();
                return [3 /*break*/, 5];
            case 3:
                error_4 = _a.sent();
                return [3 /*break*/, 5];
            case 4:
                $("#fs_button_loader_wrapper1").show();
                return [7 /*endfinally*/];
            case 5: return [2 /*return*/];
        }
    });
}); };
var cache = new Map();
function fetchEncryptedFileMemoized(note, index) {
    return __awaiter(this, void 0, void 0, function () {
        var cacheKey, result;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    cacheKey = note.id;
                    if (cache.has(cacheKey)) {
                        return [2 /*return*/, { result: cache.get(cacheKey), index: index }];
                    }
                    return [4 /*yield*/, fetchEncryptedFile(note)];
                case 1:
                    result = _a.sent();
                    cache.set(cacheKey, result);
                    return [2 /*return*/, { result: result, index: index }];
            }
        });
    });
}
function fetchEncryptedFile(cid) {
    return __awaiter(this, void 0, void 0, function () {
        var response, data, error_5;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    _a.trys.push([0, 3, , 4]);
                    return [4 /*yield*/, fetch("https://arweave.net/".concat(cid))];
                case 1:
                    response = _a.sent();
                    return [4 /*yield*/, response.json()];
                case 2:
                    data = _a.sent();
                    // console.log(data);
                    return [2 /*return*/, data];
                case 3:
                    error_5 = _a.sent();
                    console.error(error_5);
                    return [3 /*break*/, 4];
                case 4: return [2 /*return*/];
            }
        });
    });
}
// Send to Arweave
function storeFiles(files) {
    return __awaiter(this, void 0, void 0, function () {
        var response, data, error_6;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    _a.trys.push([0, 3, , 4]);
                    return [4 /*yield*/, fetch('https://arweavephiliasocial.replit.app', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'Accept': 'application/json'
                            },
                            body: JSON.stringify({
                                files: files
                            })
                        })];
                case 1:
                    response = _a.sent();
                    return [4 /*yield*/, response.json()];
                case 2:
                    data = _a.sent();
                    // console.log(data.cid)
                    return [2 /*return*/, data.cid];
                case 3:
                    error_6 = _a.sent();
                    return [3 /*break*/, 4];
                case 4: return [2 /*return*/];
            }
        });
    });
}
;
var global_chat_space_key;
// Audio Transcoding
$('#stop_recording').hide();
var mediaRecorder;
$("#voice_recording").on('click', function () { return __awaiter(void 0, void 0, void 0, function () {
    return __generator(this, function (_a) {
        mediaRecorder = new Recorder();
        mediaRecorder.start();
        $('#voice_recording').hide();
        $('#stop_recording').show();
        return [2 /*return*/];
    });
}); });
$("#stop_recording").on('click', function () { return __awaiter(void 0, void 0, void 0, function () {
    var blob, fileSize, file;
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0:
                $('#voice_recording').show();
                $('#stop_recording').hide();
                mediaRecorder.stop();
                blob = mediaRecorder.getWAVBlob();
                fileSize = blob.size / (1024 * 1024);
                if (fileSize > 30) {
                    $("#anchor_file_names").append("\n    <div class=\"file_name\">\n    <div id=\"chat_space\">Max audio duration reached.</div>\n    <div class=\"line-break0\"></div>\n    </div>\n    ");
                    setTimeout(function () {
                        $("#chat_space").remove();
                    }, 3000);
                    return [2 /*return*/];
                }
                file = new File([blob], "".concat(uuid_generate(), ".wav"));
                // Display the filename in the UI and encrypt the uploaded file
                $("#anchor_file_names").append("\n    <div class=\"file_name\">\n    ".concat(file.name, "\n    <div class=\"line-break0\"></div>\n    </div>\n    "));
                return [4 /*yield*/, encryptUploadedFile("", file, "audio/wav")];
            case 1:
                _a.sent();
                mediaRecorder.destroy().then(function () {
                    mediaRecorder = null;
                });
                return [2 /*return*/];
        }
    });
}); });
$('#lock_mess').on('click', function () {
    return __awaiter(this, void 0, void 0, function () {
        var encryption_1, timestamp_box, replaced_message, complete_message, blob, file, error_7;
        var _this = this;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    _a.trys.push([0, 3, , 4]);
                    encryption_1 = new Encryption(chat_space_private);
                    if (!(main_message.html().length > 0)) return [3 /*break*/, 2];
                    timestamp_box = $("#association_algo_password4").val().toString();
                    replaced_message = main_message.html().toString().replace(/<br>/g, "!@##@!");
                    complete_message = "".concat(timestamp_box, ": ").concat(replaced_message);
                    blob = new Blob([complete_message], { type: 'text/plain' });
                    file = new File([blob], "".concat(uuid_generate(), ".txt"));
                    return [4 /*yield*/, encryptUploadedFile("".concat(colorPicker.color.hexString), file, "text/plain")];
                case 1:
                    _a.sent();
                    _a.label = 2;
                case 2:
                    ;
                    if (uploadedFiles.length > 0) {
                        $("#wrapper_message_tools1").hide();
                        $("#wrapper_message_tools2").hide();
                        $('#fs_button_loader_wrapper1').append("\n      <div class=\"chat_space\" id=\"a_message\">Working...</div>\n      ");
                        $("#fs_button_loader_wrapper1").show();
                        // $("#fs_button_loader_wrapper2").show();
                        storeFiles(uploadedFiles).then(function (cid_res) { return __awaiter(_this, void 0, void 0, function () {
                            function createRecord() {
                                return __awaiter(this, void 0, void 0, function () {
                                    return __generator(this, function (_a) {
                                        switch (_a.label) {
                                            case 0: return [4 /*yield*/, collectionReference.create([message_id, global_chat_space_key, epochTimestamp, cid_encrypted_enc])];
                                            case 1:
                                                _a.sent();
                                                return [2 /*return*/];
                                        }
                                    });
                                });
                            }
                            var epochTimestamp, message_id, uint8Array_cid, cid_encrypted, cid_encrypted_enc;
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0:
                                        epochTimestamp = Math.floor(new Date().getTime() / 1000);
                                        message_id = password().replace(/=+$/, '');
                                        uint8Array_cid = new TextEncoder().encode(cid_res);
                                        return [4 /*yield*/, encryption_1.encrypt(uint8Array_cid)];
                                    case 1:
                                        cid_encrypted = _a.sent();
                                        cid_encrypted_enc = vec_to_base64(cid_encrypted).replace(/=+$/, '');
                                        createRecord().then(function () {
                                            $("#wrapper_message_tools1").show();
                                            $("#wrapper_message_tools2").show();
                                            uploadedFiles = [];
                                            main_message.text("");
                                            $('.file_name').text("");
                                            $("#a_message").remove();
                                        });
                                        return [2 /*return*/];
                                }
                            });
                        }); });
                    }
                    ;
                    return [3 /*break*/, 4];
                case 3:
                    error_7 = _a.sent();
                    return [3 /*break*/, 4];
                case 4:
                    ;
                    return [2 /*return*/];
            }
        });
    });
});
var fetch_data_links = [];
var fetch_data_links_ids = [];
function fetchData_ipfs(link) {
    var index = fetch_data_links_ids.indexOf(link);
    // If the id is not found in the array, return null
    if (index === -1)
        return null;
    // Otherwise, return the corresponding element from the array_link array
    return fetch_data_links[index];
}
;
var counting_separator = 1;
function unlock_button(links) {
    return __awaiter(this, void 0, void 0, function () {
        var lineBreak0, lineBreak1, separator, counter, mess_elem, unlockElem, svgButton;
        return __generator(this, function (_a) {
            lineBreak0 = $('<div>', { class: 'line-break0' });
            lineBreak1 = $('<div>', { class: 'line-break0' });
            separator = $('<div>', { class: 'separator' });
            counter = $('<div>', { class: 'separator_counter', id: "separator_counter_".concat(links), text: "".concat(counting_separator++) });
            svgButton = $("\n  <i class=\"fa-solid fa-user-lock\"></i>\n");
            mess_elem = $('<div>', { class: 'mess_elem', id: "".concat(links, "_anchor") });
            unlockElem = $('<div>', { class: 'chat_space unlockElem', id: "".concat(links) })
                .append(svgButton);
            $(".text_area_data")
                .append(lineBreak0)
                .append(mess_elem).append(unlockElem)
                .append(lineBreak1)
                .append(counter).append(separator);
            return [2 /*return*/];
        });
    });
}
$(".text_area_data").on('click', function (event) {
    // let separator_counter = [];
    var target = $(event.target);
    var unlockElem = target.closest('.unlockElem');
    if (!unlockElem.length)
        return;
    var id = unlockElem.attr('id');
    var separator_count_text = $("#separator_counter_".concat(id)).text();
    $("#separator_counter_".concat(id)).text("Decrypting...");
    var ipfs_data = fetchData_ipfs(id);
    setTimeout(function () {
        get_ipfs_data(id, ipfs_data, separator_count_text);
    }, 50);
});
function listRecordsWithFilter(chat_id) {
    return __awaiter(this, void 0, void 0, function () {
        var records;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, collectionReference
                        .where("name", "==", "".concat(chat_id))
                        .sort("time", "asc")
                        .limit(10000)
                        .get()];
                case 1:
                    records = _a.sent();
                    return [2 /*return*/, records];
            }
        });
    });
}
var mess_count_var_loop = 0;
var previous_mess_loop = 0;
function get_latest_note() {
    return __awaiter(this, void 0, void 0, function () {
        var _this = this;
        return __generator(this, function (_a) {
            // console.log(previous_mess_loop)
            collectionReference
                .where("name", "==", "".concat(global_chat_space_key))
                .sort("time", "asc")
                .limit(10000)
                .onSnapshot(function (newDoc) { return __awaiter(_this, void 0, void 0, function () {
                var elements, lastElement, error_8;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            _a.trys.push([0, 2, , 3]);
                            return [4 /*yield*/, loop_algorand()];
                        case 1:
                            _a.sent();
                            elements = document.querySelectorAll('.separator');
                            lastElement = elements[elements.length - 1];
                            lastElement.scrollIntoView();
                            return [3 /*break*/, 3];
                        case 2:
                            error_8 = _a.sent();
                            return [3 /*break*/, 3];
                        case 3: return [2 /*return*/];
                    }
                });
            }); }, function (err) {
                // Optional error handler
            });
            return [2 /*return*/];
        });
    });
}
function loop_algorand() {
    return __awaiter(this, void 0, void 0, function () {
        var array_notes, encryption;
        var _this = this;
        return __generator(this, function (_a) {
            array_notes = [];
            encryption = new Encryption(chat_space_private);
            // const chat_id = await get_chat_space_key();
            listRecordsWithFilter(global_chat_space_key).then(function (records) {
                records.data.map(function (x) {
                    // console.log(x.data.port)
                    var message_algo_main_sanitized = sanitize_base64(x.data.port);
                    encryption.decrypt(message_algo_main_sanitized)
                        .then(function (decrypted_algo_main) {
                        var decrypted_algo_main_decoded = decoder.decode(decrypted_algo_main);
                        array_notes.push(decrypted_algo_main_decoded);
                    });
                });
            }).then(function () { return __awaiter(_this, void 0, void 0, function () {
                var set_array_notes, set_array_notes_len, latestMessages;
                return __generator(this, function (_a) {
                    set_array_notes = array_notes;
                    set_array_notes_len = set_array_notes.length;
                    if (previous_mess_loop === 0) {
                        previous_mess_loop = array_notes.length;
                        // console.log(previous_mess_loop)
                        processArrayNotes(array_notes);
                    }
                    ;
                    if (set_array_notes_len > previous_mess_loop) {
                        mess_count_var_loop = set_array_notes_len - previous_mess_loop;
                        latestMessages = set_array_notes.slice(-mess_count_var_loop);
                        // console.log(latestMessages)
                        processArrayNotes(latestMessages);
                        previous_mess_loop = set_array_notes_len;
                    }
                    ;
                    return [2 /*return*/];
                });
            }); });
            return [2 /*return*/];
        });
    });
}
;
var reader = new FileReader();
function get_ipfs_data(id, ipfs_data, separator_count_text) {
    return __awaiter(this, void 0, void 0, function () {
        var encryption, decrypted_hex, decrypted_label, decrypted_hex_decoded_1, decrypted_label_decoded_1, decrypted_data_1, error_9;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    _a.trys.push([0, 4, , 5]);
                    $("#".concat(id)).remove();
                    encryption = new Encryption(chat_space_private);
                    return [4 /*yield*/, encryption.decrypt(base64_to_vec(ipfs_data.fh))];
                case 1:
                    decrypted_hex = _a.sent();
                    return [4 /*yield*/, encryption.decrypt(base64_to_vec(ipfs_data.fl))];
                case 2:
                    decrypted_label = _a.sent();
                    decrypted_hex_decoded_1 = decoder.decode(decrypted_hex);
                    decrypted_label_decoded_1 = decoder.decode(decrypted_label);
                    return [4 /*yield*/, encryption.decrypt(base64_to_vec(ipfs_data.fd))];
                case 3:
                    decrypted_data_1 = _a.sent();
                    reader.readAsDataURL(new Blob([decrypted_data_1]));
                    reader.onloadend = function () {
                        try {
                            var formatMIMETypes = {
                                "audio/mpeg": "audio/mpeg",
                                "audio/mp3": "audio/mp3",
                                "audio/x-m4a": "audio/x-m4a",
                                "audio/wav": "audio/wav",
                                "audio/flac": "audio/flac",
                                "audio/webm;codecs=opus": "audio/webm;codecs=opus",
                                "video/mp4": "video/mp4",
                                "video/quicktime": "video/quicktime",
                                "image/png": "image/png",
                                "image/jpeg": "image/jpeg",
                                "text/plain": "text/plain",
                                "application/pdf": "application/pdf",
                            };
                            var format = decrypted_label_decoded_1;
                            var mimeType = formatMIMETypes[format];
                            if (mimeType.startsWith("audio/")) {
                                var audioBlob = new Blob([decrypted_data_1], { type: mimeType });
                                var audioUrl = URL.createObjectURL(audioBlob);
                                $.when($("#".concat(id, "_anchor")).append($('<audio>', { src: audioUrl, class: "rendered_audio", style: "--plyr-audio-controls-background: #eee;" }))).done(function () {
                                    $("#separator_counter_".concat(id)).text(separator_count_text);
                                    Plyr.setup(".rendered_audio", {
                                        controls: ['play', 'progress', 'current-time', 'mute', 'settings'],
                                        autoplay: false,
                                        displayDuration: true
                                    });
                                });
                            }
                            else if (mimeType.startsWith("video/")) {
                                var videoBlob = new Blob([decrypted_data_1], { type: mimeType });
                                var videoUrl = URL.createObjectURL(videoBlob);
                                // const set_video_id = `${id}_video`;
                                $.when($("#".concat(id, "_anchor")).append($('<video>', { src: videoUrl, class: "rendered_vid" }))).done(function () {
                                    $("#separator_counter_".concat(id)).text(separator_count_text);
                                    Plyr.setup('.rendered_vid', {
                                        controls: ['play', 'progress', 'current-time', 'mute', 'settings', 'fullscreen'],
                                        autoplay: false,
                                    });
                                });
                            }
                            else if (mimeType.startsWith("image/")) {
                                $.when($("#".concat(id, "_anchor")).append($('<img>', { src: reader.result, class: "rendered_img" }))).done(function () {
                                    $("#separator_counter_".concat(id)).text(separator_count_text);
                                });
                            }
                            else if (mimeType.startsWith("text/")) {
                                var decrypted_text_decoded = decoder.decode(decrypted_data_1);
                                // Replace the ID with <br>
                                var replaced_text = decrypted_text_decoded.replace(/!@##@!/g, "<br>");
                                // Find URLs using regular expression and replace them with anchor tags
                                var urlRegex = /((https?:\/\/)|(www\.))[^<\s]+/g;
                                var linked_text = replaced_text.replace(urlRegex, function (url) {
                                    var urlWithProtocol = url.startsWith('http') ? url : 'http://' + url;
                                    return "<a href=\"".concat(urlWithProtocol, "\" target=\"_blank\">").concat(url, "</a>");
                                });
                                // Create a new jQuery object with the replaced text as its HTML content
                                var text = $('<div>').html(linked_text);
                                text.css('color', decrypted_hex_decoded_1);
                                // $(`#${id}_anchor`).append(text);
                                $.when($("#".concat(id, "_anchor")).append(text)).done(function () {
                                    $("#separator_counter_".concat(id)).text(separator_count_text);
                                });
                            }
                            else if (mimeType.startsWith("application/")) {
                                var pdfBlob = new Blob([decrypted_data_1], { type: 'application/pdf' });
                                var pdfUrl = URL.createObjectURL(pdfBlob);
                                $.when($("#".concat(id, "_anchor")).append("<a href=\"".concat(pdfUrl, "\" target=\"_blank\"><span class=\"chat_space fa-solid fa-file-pdf\"></span></a>"))).done(function () {
                                    $("#separator_counter_".concat(id)).text(separator_count_text);
                                });
                            }
                            ;
                        }
                        catch (error) {
                            // console.log(error)
                        }
                    };
                    return [3 /*break*/, 5];
                case 4:
                    error_9 = _a.sent();
                    return [3 /*break*/, 5];
                case 5: return [2 /*return*/];
            }
        });
    });
}
$('#latest_mess').on('click', function () {
    return __awaiter(this, void 0, void 0, function () {
        var elements, lastElement;
        return __generator(this, function (_a) {
            try {
                elements = document.querySelectorAll('.separator');
                lastElement = elements[elements.length - 1];
                lastElement.scrollIntoView();
            }
            catch (error) {
                // console.log(error) 
            }
            return [2 /*return*/];
        });
    });
});
$("#blur_mess").on('click', function () {
    if ($("#glass").length) {
        $("#glass").remove();
    }
    else {
        $("#wrapper_glass").append("\n        \n      <div id=\"glass\"></div>\n\n      ");
    }
});
$('#refresh').on('click', function () {
    $("#refresh").addClass("animated");
    // Open the new window after the transition or animation has completed
    setTimeout(function () {
        window.location.reload();
    }, 500);
});
function handleUpload() {
    return __awaiter(this, void 0, void 0, function () {
        var file, allowedTypes, error_10;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    file = input.files[0];
                    allowedTypes = [
                        "audio/mpeg",
                        "audio/x-m4a",
                        "audio/wav",
                        "audio/flac",
                        "audio/webm;codecs=opus",
                        "audio/mp3",
                        "video/mp4",
                        "video/quicktime",
                        "image/png",
                        "image/jpeg",
                        "text/plain",
                        "application/pdf",
                    ];
                    _a.label = 1;
                case 1:
                    _a.trys.push([1, 6, , 7]);
                    if (!(file.size > 60 * 1024 * 1024)) return [3 /*break*/, 2];
                    return [3 /*break*/, 5];
                case 2:
                    if (!!allowedTypes.includes(file.type)) return [3 /*break*/, 3];
                    return [3 /*break*/, 5];
                case 3:
                    $("#anchor_file_names").append("\n        <div class=\"file_name\">\n          ".concat(file.name, "\n          <div class=\"line-break0\"></div>\n        </div>\n      "));
                    return [4 /*yield*/, encryptUploadedFile("", file, file.type)];
                case 4:
                    _a.sent();
                    _a.label = 5;
                case 5:
                    ;
                    return [3 /*break*/, 7];
                case 6:
                    error_10 = _a.sent();
                    return [3 /*break*/, 7];
                case 7:
                    ;
                    return [2 /*return*/];
            }
        });
    });
}
;