export const showAssetsBrowser = () => {
    const newWindow = window.open('', 'Asset browser', `width=${screen.width * 0.8},height=${screen.height * 0.8}`);
    let data = null;
    // type dataTypes = 'animations' | 'audio' | 'environments' | 'materials' | 'meshes' | 'prefabs';
    let dataType = 'prefabs';
    let filterString = '';
    let showHidden = false;
    let gridElement = null;
    let audioPlayer = null;
    let selectedTag = '';
    let sortedData = {};
    let tagsData = {};
    let audioTimer = null;
    const defaultThumbnail = 'https://cdn.hibervr.com/hiber2_prod/textures/en_b_cube_01_thumbnail/v1.0.0/en_b_cube_01_thumbnail.256.png';
    const baseMarkup = `<!DOCTYPE html>
    <html>
      <head>
        <title>Assets Browser</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <style>
          html, body {
            margin: 0;
            padding: 10px;
            background-color: #333;
            font-family: sans-serif;
            font-size: 14px;
          }

          select,
          input[type="text"],
          input[type="password"],
          input[type="email"],
          input[type="number"] {
            background-color: #666;
            border-radius: 10px;
            color: #fff;
            padding: 7px 10px;
            border: none;
            margin-right: 10px;
          }

          .top {
            position: fixed;
            background-color: #222;
            width: 100%;
            left: 0;
            top: 0;
            padding: 10px 20px;
            z-index: 10;
            color: #fff;
            display: flex;
            align-items: center;
            justify-content: center;
          }

          .top .top-inner {
            text-align: center;
            max-width: 1000px;
            margin: 0 auto;
          }

          .top .info {
            margin-top: 10px;
            font-size: 16px;
          }

          .grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            grid-gap: 10px;
            grid-auto-rows: auto;
            margin-top: 80px;
          }

          .item {
            background-color: #444;
            color: #fff;
            border-radius: 10px;
            margin: 5px;
            text-align: center;
            box-sizing: border-box;
            padding: 10px;
            cursor: pointer;
            max-width: 500px;
          }
          .item .item__name {
            font-size: 16px;
            font-weight: bold;
          }
          .item .item__id {
            font-size: 12px;
            font-style: italic;
            text-overflow: ellipsis;
            overflow: hidden;
          }
          .item img {
            width: 100%;
            border-radius: 10px;
            margin-bottom: 10px;
          }
          .item.hidden {
            opacity: 0.8;
            color: #aaa;
          }
          .item-inner {
            position: relative;
          }
          
          .play-button {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 60px;
            height: 60px;
            background-color: rgba(0, 0, 0, 0.7);
            border: 2px solid white;
            border-radius: 50%;
            cursor: pointer;
          }
          
          .play-button::before {
            content: "";
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-40%, -50%) rotate(0deg);
            width: 0;
            height: 0;
            border-top: 15px solid transparent;
            border-bottom: 15px solid transparent;
            border-left: 25px solid white;
          }
          
        </style>
      </head>
      <body>
      <div class="top">
        <div class="top-inner">
            <div class="filter">
              <input type="text" value="" class="filterString">
              <select class="dataType">
                <option value="prefabs">Prefabs</option>
                <option value="materials">Materials</option>
                <option value="audio">Audio</option>
                <option value="environments">Environments</option>
              </select>
              <select id="tags-dropdown">
                <option value="">All tags</option>
              </select>
              <input type="checkbox" class="showHidden"> Show hidden
            </div>
            <div class="info">
              Click to copy id to clipboard
            </div>
        </div>
      </div>
        <div class="grid"></div>
      </body>
    </html>`;
    const getData = (callback) => {
        if (data) {
            callback(data);
        }
        else {
            const xhr = new XMLHttpRequest();
            xhr.open('GET', 'https://cdn.hibervr.com/hiber2/bookkeeping/metadata-v2.generated.json');
            xhr.onload = () => {
                if (xhr.status === 200) {
                    data = JSON.parse(xhr.responseText);
                    callback(data);
                }
                else {
                    console.log('Request failed');
                }
            };
            xhr.send();
        }
    };
    const showMessage = (message) => {
        if (!newWindow)
            return;
        const div = newWindow.document.createElement('div'); // Create a new div element
        div.innerHTML = message; // Set the text content of the div element to the message
        div.style.position = 'fixed'; // Set the position of the div element to fixed
        div.style.top = '50%'; // Set the top position of the div element to 50%
        div.style.left = '50%'; // Set the left position of the div element to 50%
        div.style.transform = 'translate(-50%, -50%)'; // Center the div element
        div.style.opacity = '1'; // Set the initial opacity of the div element to 1
        div.style.transition = 'opacity 1s'; // Set the transition property to fade out over 1 second
        div.style.backgroundColor = '#fff'; // Set the background color of the div element to white
        div.style.borderRadius = '10px'; // Set the border radius of the div element to 10 pixels
        div.style.padding = '20px'; // Add some padding to the div element for better readability
        newWindow.document.body.appendChild(div); // Append the div element to the document body
        setTimeout(() => {
            div.style.opacity = '0'; // Set the opacity of the div element to 0 to fade it out
            setTimeout(() => {
                newWindow.document.body.removeChild(div); // Remove the div element from the document body
            }, 1000); // Wait for 1 second before removing the div element
        }, 1000); // Wait for 1 second before fading out the div element
    };
    const playAudio = (url) => {
        if (audioTimer) {
            clearTimeout(audioTimer);
        }
        if (audioPlayer) {
            audioPlayer.pause();
        }
        audioPlayer = new Audio(url);
        audioPlayer.play();
        audioTimer = setTimeout(() => {
            if (audioPlayer)
                audioPlayer.pause();
        }, 4000);
    };
    const replaceUnderscoreAndCapitalize = (str) => {
        const words = str.split('_');
        const capitalizedWords = words.map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase());
        return capitalizedWords.join(' ');
    };
    const getItemData = (itemData) => {
        if (dataType === 'prefabs') {
            return {
                hidden: itemData.visibility !== 'VISIBLE',
                thumbnail: itemData.prefab.thumbnailID === 'default_thumbnail'
                    ? defaultThumbnail
                    : `https://cdn.hibervr.com/hiber2_prod/textures/${itemData.prefab.thumbnailID}/v1.0.0/${itemData.prefab.thumbnailID}.256.png`,
                label: itemData.displayName,
                id: itemData.id,
                tags: itemData.tags || [],
                url: '',
            };
        }
        else if (dataType === 'materials') {
            return {
                hidden: !itemData.displayName,
                thumbnail: !itemData.material.thumbnailTexID
                    ? defaultThumbnail
                    : `https://cdn.hibervr.com/hiber2_prod/textures/${itemData.material.thumbnailTexID}/v1.0.0/${itemData.material.thumbnailTexID}.256.png`,
                label: itemData.displayName || itemData.id,
                id: itemData.id,
                tags: itemData.tags || [],
                url: '',
            };
        }
        else if (dataType === 'environments') {
            return {
                hidden: itemData.visibility !== 'VISIBLE',
                thumbnail: !itemData.environment.thumbnailID
                    ? defaultThumbnail
                    : `https://cdn.hibervr.com/hiber2_prod/textures/${itemData.environment.thumbnailID}/v1.0.0/${itemData.environment.thumbnailID}.256.png`,
                label: replaceUnderscoreAndCapitalize(itemData.displayName || itemData.id),
                id: itemData.id,
                tags: itemData.tags || [],
                url: '',
            };
        }
        else if (dataType === 'audio') {
            return {
                hidden: itemData.visibility !== 'VISIBLE',
                thumbnail: !itemData.thumbnailID
                    ? defaultThumbnail
                    : `https://cdn.hibervr.com/hiber2_prod/textures/${itemData.thumbnailID}/v1.0.0/${itemData.thumbnailID}.256.png`,
                label: replaceUnderscoreAndCapitalize(itemData.displayName || itemData.id),
                id: itemData.id,
                tags: itemData.tags || [],
                url: 'https://cdn.hibervr.com/hiber2_prod/audio/' + itemData.id + '/v1.0.0/' + itemData.id + '.mp3',
            };
        }
        return null;
    };
    const getItemMarkup = (data) => {
        const hasUrl = !!data.url;
        const playButton = hasUrl ? `<div class="play-button" data-url="${data.url}"></div>` : '';
        return `
      <div class="item ${data.hidden ? 'hidden' : ''}">
        <div class="item-inner">
          <img src="${data.thumbnail}"  onerror="this.onerror=null;this.src='${defaultThumbnail}';">
          <div class="item__name">${data.label}</div>
          <div class="item__id">${data.id}</div>
          ${playButton}
        </div>
      </div>
    `;
    };
    const dataCleanup = () => {
        if (!newWindow) {
            return;
        }
        // Fetch and sort data
        let sortedArray = [];
        let tags = [];
        for (let index = 0; index < data[dataType].length; index++) {
            const itemData = getItemData(data[dataType][index]);
            if (itemData && itemData.label) {
                sortedArray.push(itemData);
                tags = [...tags, ...itemData.tags];
            }
        }
        // Remove duplicated tags from array
        tags = [...new Set(tags)];
        // Sort tags by name
        tags.sort((a, b) => {
            if (a < b) {
                return -1;
            }
            if (a > b) {
                return 1;
            }
            return 0;
        });
        // Remove tag 'new' and add it to the start of the array
        const newTagIndex = tags.indexOf('new');
        if (newTagIndex > -1) {
            tags.splice(newTagIndex, 1);
            tags.unshift('new');
        }
        // Sort items by name
        sortedArray.sort((a, b) => {
            if (a.label < b.label) {
                return -1;
            }
            if (a.label > b.label) {
                return 1;
            }
            return 0;
        });
        sortedData[dataType] = sortedArray;
        tagsData[dataType] = tags;
    };
    const refill = () => {
        if (audioPlayer) {
            audioPlayer.pause();
        }
        if (!newWindow)
            return;
        if (!sortedData[dataType]) {
            dataCleanup();
        }
        let itemMarkup = '';
        for (let index = 0; index < sortedData[dataType].length; index++) {
            const itemData = sortedData[dataType][index];
            if (itemData) {
                const markup = getItemMarkup(itemData);
                const populate = () => {
                    if (itemData.label.toLowerCase().includes(filterString.toLowerCase())) {
                        if (!itemData.hidden) {
                            itemMarkup += markup;
                        }
                        else if (showHidden) {
                            itemMarkup += markup;
                        }
                    }
                };
                // Filter by tag
                if (selectedTag && itemData.tags.indexOf(selectedTag) !== -1) {
                    populate();
                }
                else if (selectedTag === '') {
                    populate();
                }
            }
        }
        if (gridElement) {
            gridElement.innerHTML = itemMarkup;
            newWindow.document.querySelectorAll('.item').forEach(item => {
                item.addEventListener('click', e => {
                    const idElement = item.querySelector('.item__id');
                    if (idElement) {
                        const id = idElement.innerHTML;
                        if (e.shiftKey && dataType === 'prefabs') {
                            const copyText = `const ${id} = create('${id}', { z: 5 }).addTo(world);`;
                            newWindow.navigator.clipboard.writeText(copyText);
                            showMessage('<b>Copied to clipboard:</b><br><code>' + copyText) + '</code>';
                        }
                        else {
                            newWindow.navigator.clipboard.writeText(id);
                            showMessage('<b>Copied to clipboard:</b><br><code>' + id) + '</code>';
                        }
                    }
                });
            });
            newWindow.document.querySelectorAll('.play-button').forEach(item => {
                item.addEventListener('click', e => {
                    e.stopPropagation();
                    const url = item.getAttribute('data-url');
                    if (url) {
                        playAudio(url);
                    }
                });
            });
        }
    };
    const tagManager = () => {
        if (!newWindow)
            return;
        const tags = tagsData[dataType];
        const tagsDropDown = newWindow.document.getElementById('tags-dropdown');
        if (tagsDropDown) {
            if (tags.length === 0) {
                tagsDropDown.style.display = 'none';
            }
            else {
                tagsDropDown.style.display = 'inline-block';
            }
            tagsDropDown.innerHTML = '<option value="">All tags</option>';
            tags.forEach((tag) => {
                const option = document.createElement('option');
                option.value = tag;
                option.text = tag;
                tagsDropDown.appendChild(option);
            });
            tagsDropDown.addEventListener('change', () => {
                selectedTag = tagsDropDown.value;
                refill();
            });
        }
    };
    const init = () => {
        if (newWindow) {
            // Find textures for particle systems
            /*
            for (let index = 0; index < data.textures.length; index++) {
              const element = data.textures[index];
              // See if the textures name contains 'particle' in it
              if (element.name.toLowerCase().includes('particle')) {
                // See if the textures name contains 'gradient' in it
                if (element.name.toLowerCase().includes('gradient')) {
                  console.log(element.name);
                } else {
                  console.log(element.name);
                }
              }
            }
            */
            newWindow.document.write(baseMarkup);
            gridElement = newWindow.document.querySelector('.grid');
            // Setup event listeners
            const dataTypeSelect = newWindow.document.querySelector('.dataType');
            if (dataTypeSelect) {
                dataTypeSelect.addEventListener('change', e => {
                    dataType = e.target.value;
                    showMessage('Showing ' + dataType + ' items');
                    selectedTag = '';
                    refill();
                    tagManager();
                });
            }
            const filterStringInput = newWindow.document.querySelector('.filterString');
            if (filterStringInput) {
                filterStringInput.addEventListener('keyup', e => {
                    filterString = e.target.value;
                    refill();
                });
            }
            const showHiddenCheckbox = newWindow.document.querySelector('.showHidden');
            if (showHiddenCheckbox) {
                showHiddenCheckbox.addEventListener('change', e => {
                    showHidden = e.target.checked;
                    refill();
                });
            }
            refill();
            tagManager();
        }
        else {
            console.log('Failed to open new window');
        }
    };
    getData(init);
};
//# sourceMappingURL=showAssetsBrowser.js.map