<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>${app['title']} - Verge3D App Manager</title>
  <%include file="head.tpl"/>
</head>

<body>
  <div class="main-panel">

    <div class="banner"></div>

    <%include file="package_indicator.tpl"/>
    <%include file="search.tpl"/>

    <%
        import os.path, urllib.parse

        dirItems = {}

        def pathToUrl(path):
            """
            Based on similary named method from server.py
            """
            path = path.replace('\\', '/')
            path = urllib.parse.quote(path, safe='/:')
            return path

        def getReducedDirName(path):
            dirName = os.path.dirname(path)
            dirParts = dirName.split(os.path.sep)
            return (os.path.sep.join(dirParts[0:2]), len(dirParts) <= 1)

        def checkCorrespondingItem(item, items):
            for i in items:
                if os.path.splitext(i['name'])[0] == os.path.splitext(item['name'])[0]:
                    return True
            return False

        for itemType in ['html', 'gltf']:
            for item in app[itemType]:
                item['type'] = itemType
                item['cut'] = False

                dirName, isRoot = getReducedDirName(item['path'])
                if not dirName in dirItems:
                    dirItems[dirName] = { 'leftItems': [], 'rightItems': [], 'isRoot': isRoot }

                dirItems[dirName]['leftItems'].append(item)

        for itemType in ['blend', 'max', 'maya']:
            for item in app[itemType]:
                item['type'] = itemType
                item['cut'] = False

                dirName, isRoot = getReducedDirName(item['path'])
                if not dirName in dirItems:
                    dirItems[dirName] = { 'leftItems': [], 'rightItems': [], 'isRoot': isRoot }

                # TODO: disable isMain for multi-material folders in server.py
                if not isRoot:
                    item['isMain'] = False

                dirItems[dirName]['rightItems'].append(item)

        for items in dirItems.values():
            leftItems = items['leftItems']
            rightItems = items['rightItems']

            numHTMLs = 0

            for i in range(len(leftItems)):
                item = leftItems[i]
                if item['type'] == 'html':
                    rightItems.insert(0, {'type': 'empty'})
                    numHTMLs = numHTMLs + 1

            if numHTMLs > 0 and items['isRoot']:
                leftItems[numHTMLs-1]['cut'] = True
                rightItems[numHTMLs-1]['cut'] = True

            for item in leftItems[numHTMLs:]:
                if not checkCorrespondingItem(item, rightItems[numHTMLs:]):
                    # '.blend' here is just for consistency, does not matter actually
                    rightItems.append({'name': os.path.splitext(item['name'])[0] + '.blend', 'type': 'placeholder'})

            for item in rightItems[numHTMLs:]:
                if not checkCorrespondingItem(item, leftItems[numHTMLs:]):
                    # '.gltf' here is just for consistency, does not matter actually
                    leftItems.append({'name': os.path.splitext(item['name'])[0] + '.gltf', 'type': 'placeholder'})

            leftItems[numHTMLs:] = sorted(leftItems[numHTMLs:], key=lambda elem: elem['name'])
            rightItems[numHTMLs:] = sorted(rightItems[numHTMLs:], key=lambda elem: elem['name'])
    %>

    <table class="app-assets-list">
      <thead>
        <tr>
          <th colspan=2>runnables</th>
          <th colspan=2>scenes</th>
        </tr>
      </thead>
      <tbody>
        % for dir in sorted(dirItems):
          <%
          leftItems = dirItems[dir]['leftItems']
          rightItems = dirItems[dir]['rightItems']
          %>

          % if not dirItems[dir]['isRoot']:
            <tr class="folder">
              <td>
                <a href="javascript:void(0);" class="open-close-folder opened" data-folder="${dir}" title="Expand/collapse folder contents"></a>
              </td>
              <td colspan=3>
                <a href="javascript:void(0);" onclick=openFile("/applications/${pathToUrl(dir)}) class="app-icon app-icon-folder-opened" title="Open folder: ${dir}"></a>
                <a href="javascript:void(0);" onclick=openFile("/applications/${pathToUrl(dir)}") class="asset-title" title="Open folder: ${dir}">${dir}</a>
              </td>
            </tr>
          % endif

          % for i, left, right in zip(range(len(leftItems)), leftItems, rightItems):
            <tr class="filterable" data-folder="${dir}">
              % if left['type'] == 'html':
                <td class="${'cell-cut' if left['cut'] else ''}">
                  % if i == 0:
                    <a href="${left['url']}" target="_blank" class="app-icon app-icon-html-main" title="Run app: ${left['path']}"></a>
                  % else:
                    <a href="${left['url']}" target="_blank" class="app-icon app-icon-html" title="Run HTML: ${left['path']}"></a>
                  % endif
                </td>
                <td class="${'cell-cut' if left['cut'] else ''}">
                  % if i == 0:
                    <a href="${left['url']}" target="_blank" class="asset-title" title="Run app: ${left['path']}">${left['name']}</a>
                  % else:
                    <a href="${left['url']}" target="_blank" class="asset-title" title="Run HTML: ${left['path']}">${left['name']}</a>
                  % endif
                </td>

              % elif left['type'] == 'gltf':
                <td>
                  <a href="${left['url']}" target="_blank" class="app-icon app-icon-gltf" title="View scene: ${left['path']}"></a>
                </td>
                <td>
                  <a href="${left['url']}" target="_blank" class="asset-title" title="View scene: ${left['path']}">${left['name']}</a>
                </td>

              % elif left['type'] == 'placeholder':
                <td>
                  <span class="app-icon app-icon-placeholder-run"></span>
                </td>
                <td>
                  <span class="asset-title asset-title-placeholder">...</span>
                </td>
              % endif

              % if right['type'] == 'blend':
                <td>
                  <a href="javascript:void(0);" onclick=openFile("${right['url']}") class="app-icon app-icon-blend${'-main' if right['isMain'] else ''}" title="Open Blender file: ${right['path']}"></a>
                </td>
                <td>
                  <a class="asset-title" href="javascript:void(0);" onclick=openFile("${right['url']}") title="Open Blender file: ${right['path']}">${right['name']}</a>
                </td>

              % elif right['type'] == 'max':
                <td>
                  <a href="javascript:void(0);" onclick=openFile("${right['url']}") class="app-icon app-icon-max${'-main' if right['isMain'] else ''}" title="Open 3ds Max file: ${right['path']}"></a>
                </td>
                <td>
                  <a class="asset-title" href="javascript:void(0);" onclick=openFile("${right['url']}") title="Open 3ds Max file: ${right['path']}">${right['name']}</a>
                </td>

              % elif right['type'] == 'maya':
                <td>
                  <a href="javascript:void(0);" onclick=openFile("${right['url']}") class="app-icon app-icon-maya${'-main' if right['isMain'] else ''}" title="Open Maya file: ${right['path']}"></a>
                </td>
                <td>
                  <a class="asset-title" href="javascript:void(0);" onclick=openFile("${right['url']}") title="Open Maya file: ${right['path']}">${right['name']}</a>
                </td>

              % elif right['type'] == 'placeholder':
                <td>
                  <span class="app-icon app-icon-placeholder-scene"></span>
                </td>
                <td>
                  <span class="asset-title asset-title-placeholder">...</span>
                </td>

              % elif right['type'] == 'empty':
                <td class="${'cell-cut' if left['cut'] else ''}"></td>
                <td class="${'cell-cut' if left['cut'] else ''}"></td>
              % endif
            </tr>
          % endfor
        % endfor
      </tbody>
      <tfoot><tr><td colspan=4>© 2017-2026 Soft8Soft</td></tr></tfoot>
    </table>
  
  </div>

  <script>

    if (localStorage.v3dManagerFolderStatus) {
        const folderStatus = JSON.parse(localStorage.v3dManagerFolderStatus)
        for (const folder in folderStatus) {
            document.querySelectorAll('table.app-assets-list tr.filterable').forEach(item => {
                if (item.dataset.folder == folder)
                    if (folderStatus[folder] == 'opened')
                        item.classList.remove('folder-item-hidden');
                    else
                        item.classList.add('folder-item-hidden');
            });

            document.querySelectorAll('table.app-assets-list a.open-close-folder').forEach(item => {
                if (item.dataset.folder == folder)
                    if (folderStatus[folder] == 'opened') {
                        item.classList.remove('closed');
                        item.classList.add('opened');
                    } else {
                        item.classList.remove('opened');
                        item.classList.add('closed');
                    }
            });
        }
    }

    function saveFolderStatus(folder, status) {
        if (!localStorage.v3dManagerFolderStatus)
            localStorage.v3dManagerFolderStatus = '{}';

        const folderStatus = JSON.parse(localStorage.v3dManagerFolderStatus)
        folderStatus[folder] = status;

        localStorage.v3dManagerFolderStatus = JSON.stringify(folderStatus);
    }

    document.querySelector('table.app-assets-list').addEventListener('click', (e) => {
        if (e.target.classList.contains('open-close-folder')) {
            const folder = e.target.dataset.folder;

            if (e.target.classList.contains('opened')) {
                e.target.classList.remove('opened');
                e.target.classList.add('closed');

                document.querySelectorAll('table.app-assets-list tr.filterable').forEach(item => {
                    if (item.dataset.folder == folder)
                        item.classList.add('folder-item-hidden');
                });

                saveFolderStatus(folder, 'closed');
            } else {
                e.target.classList.remove('closed');
                e.target.classList.add('opened');

                document.querySelectorAll('table.app-assets-list tr.filterable').forEach(item => {
                    if (item.dataset.folder == folder)
                        item.classList.remove('folder-item-hidden');
                });

                saveFolderStatus(folder, 'opened');
            }

            applyTableHeightHack();
        }
    });
  </script>

  <%include file="toolbar.tpl"/>
  <%include file="toolbar_app.tpl"/>
  <%include file="dialog_publishing.tpl"/>
  <%include file="dialog_qr_code.tpl"/>

</body>
</html>
