<%!
import json
import os.path
def filename(text):
    name = os.path.basename(text)
    if len(name) > 35:
        return name[0:35] + '...'
    else:
        return name
%>

<%inherit file="dialog.tpl"/>
<%namespace name="utils" file="utils.tpl"/>

<%block name="blkDialogId">diaAppSettings</%block>

<%block name="blkDialogHeader">
  Application Settings
</%block>

<%block name="blkDialogHeaderHelp">
  ${utils.genManualButton('introduction/App-Manager.html#app_settings_general_tab', 'diaAppSettingsHelp')}
</%block>

<%block name="blkDialogContent">
  <div class="settings-left-panel app-settings">
    <div class="settings-left-item settings-left-item-active" id="settingsItemGeneral">General</div>
    <div class="settings-left-item" id="settingsItemPreloader">Preloader</div>
    <div class="settings-left-item" id="settingsItemUI">UI</div>
    <div class="settings-left-item" id="settingsItemAnnotations">Annotations</div>
    <div class="settings-left-item" id="settingsItemSharing">Sharing</div>
    <div class="settings-left-item" id="settingsItemErrors">Errors</div>
    <div class="settings-left-item" id="settingsItemPWA">PWA</div>
  </div>

  <form action="" id="settingsForm" class="settings-form app-settings">

    <input type="hidden" name="app" value="${app['name']}">

    <div class="app-settings-general">
      <table class="app-settings">
        % if 'title' in settings:
          <tr>
            <td>Title:</td>
            <td>
              <input type="text" name="title" value="${settings['title']}" class="app-settings-text">
            </td>
          </tr>
        % endif
        % if 'description' in settings:
          <tr>
            <td>Description:</td>
            <td>
              <textarea name="description" cols="40" rows="3" class="app-settings-textarea">${settings['description']}</textarea>
            </td>
          </tr>
        % endif
        % if 'favicon48' in settings:
          <tr>
            <td>Favicon 48x48:</td>
            <td>
              <label for="favicon48ImageSelector" class="app-settings-img-label">
                <div class="app-settings-img-name">${settings['favicon48'] | filename}</div>
                <div class="app-settings-img-browse"></div>
              </label>
              <input type="file" id="favicon48ImageSelector" accept="image/png" class="hidden">
              <div class="app-settings-img-cont small">
                <img src="${settings['favicon48']}" id="favicon48" class="app-settings-img small">
              </div>
            </td>
          </tr>
        % endif
        % if 'favicon180' in settings:
          <tr>
            <td>Safari 180x180:</td>
            <td>
              <label for="favicon180ImageSelector" class="app-settings-img-label large">
                <div class="app-settings-img-name">${settings['favicon180'] | filename}</div>
                <div class="app-settings-img-browse"></div>
              </label>
              <input type="file" id="favicon180ImageSelector" accept="image/png" class="hidden">
              <div class="app-settings-img-cont large">
                <img src="${settings['favicon180']}" id="favicon180" class="app-settings-img large">
              </div>
            </td>
          </tr>
        % endif
        % if 'favicon192' in settings:
          <tr>
            <td>Chrome 192x192:</td>
            <td>
              <label for="favicon192ImageSelector" class="app-settings-img-label large">
                <div class="app-settings-img-name">${settings['favicon192'] | filename}</div>
                <div class="app-settings-img-browse"></div>
              </label>
              <input type="file" id="favicon192ImageSelector" accept="image/png" class="hidden">
              <div class="app-settings-img-cont large">
                <img src="${settings['favicon192']}" id="favicon192" class="app-settings-img large">
              </div>
            </td>
          </tr>
        % endif
        % if 'favicon512' in settings:
          <tr>
            <td>Chrome 512x512:</td>
            <td>
              <label for="favicon512ImageSelector" class="app-settings-img-label large">
                <div class="app-settings-img-name">${settings['favicon512'] | filename}</div>
                <div class="app-settings-img-browse"></div>
              </label>
              <input type="file" id="favicon512ImageSelector" accept="image/png" class="hidden">
              <div class="app-settings-img-cont large">
                <img src="${settings['favicon512']}" id="favicon512" class="app-settings-img large">
              </div>
            </td>
          </tr>
        % endif
      </table>
    </div>

    <div class="app-settings-preloader hidden">
      <table class="app-settings">
        % if 'preloaderImage' in settings:
          <tr>
            <td>Image:</td>
            <td>
              <label for="preloaderImageSelector" class="app-settings-img-label large">
                <div class="app-settings-img-name">${settings['preloaderImage'] | filename}</div>
                <div class="app-settings-img-browse"></div>
              </label>
              <input type="file" id="preloaderImageSelector" accept="image/*" class="hidden">
              <div class="app-settings-img-cont large">
                <img src="${settings['preloaderImage']}" id="preloaderImage" class="app-settings-img large">
              </div>
            </td>
          </tr>
        % endif
        % if 'preloaderImageWidth' in settings and 'preloaderImageHeight' in settings:
          <tr>
            <td>Image Size:</td>
            <td>
              <label for="preloaderImageWidth" class="app-settings-input-label">Width</label>
              <div class="pixel-units sameline"><input type="number" name="preloaderImageWidth" id="preloaderImageWidth" value="${settings['preloaderImageWidth']}" min=0 max=9999 class="dialog-num-input"></div>
              <label for="preloaderImageHeight" class="app-settings-input-label">Height</label>
              <div class="pixel-units sameline"><input type="number" name="preloaderImageHeight" id="preloaderImageHeight" value="${settings['preloaderImageHeight']}" min=0 max=9999 class="dialog-num-input"></div>
            </td>
          </tr>
        %endif
        % if 'preloaderBarSolidColor' in settings or 'preloaderBarGradientColor' in settings or 'preloaderBarCSSColor' in settings:
          <tr>
            <td>Bar Color:</td>
            <td>
              <div>
                <input type="radio" name="preloaderBarType" id="preloaderBarType1" value="solid" ${'checked' if 'preloaderBarSolidColor' in settings else ''}>
                <label for="preloaderBarType1" class="app-settings-input-label">Solid Color</label>
                <input type="color" name="preloaderBarSolidColor" value="${settings['preloaderBarSolidColor'] if 'preloaderBarSolidColor' in settings else '#1458ae'}" class="app-settings-color-input">
              </div>
              <div>
                <input type="radio" name="preloaderBarType" id="preloaderBarType2" value="gradient" ${'checked' if 'preloaderBarGradientColor' in settings else ''}>
                <label for="preloaderBarType2" class="app-settings-input-label">Gradient Color</label>
                <label for="preloaderBarGradientColor" class="app-settings-input-label">From</label>
                <input type="color" name="preloaderBarGradientColor" id="preloaderBarGradientColor" value="${settings['preloaderBarGradientColor'] if 'preloaderBarGradientColor' in settings else '#1458ae'}" class="app-settings-color-input">
                <label for="preloaderBarGradientColor2" class="app-settings-input-label">To</label>
                <input type="color" name="preloaderBarGradientColor2" id="preloaderBarGradientColor2" value="${settings['preloaderBarGradientColor2'] if 'preloaderBarGradientColor2' in settings else '#4388e0'}" class="app-settings-color-input">
              </div>
              <div>
                <input type="radio" name="preloaderBarType" id="preloaderBarType3" value="css" ${'checked' if 'preloaderBarSolidColor' not in settings and 'preloaderBarGradientColor' not in settings and 'preloaderBarCSSColor' in settings else ''}>
                <label for="preloaderBarType3" class="app-settings-input-label">CSS</label>
                <input type="text" name="preloaderBarCSSColor" value="${settings['preloaderBarCSSColor'] if 'preloaderBarCSSColor' in settings else 'linear-gradient(90deg, #1458ae, #4388e0)'}" class="app-settings-inline-text" spellcheck="false">
              </div>
            </td>
          </tr>
        % endif
        % if 'preloaderBarBorderColor' in settings:
          <tr>
            <td>Bar Border Color:</td>
            <td>
              <input type="color" name="preloaderBarBorderColor" value="${settings['preloaderBarBorderColor'] if 'preloaderBarBorderColor' in settings else '#2b70c7'}" class="app-settings-color-input">
            </td>
          </tr>
        %endif
        % if 'preloaderBarHeight' in settings:
          <tr>
            <td>Bar Height:</td>
            <td>
              <div class="pixel-units"><input type="number" name="preloaderBarHeight" value="${settings['preloaderBarHeight']}" min=0 class="dialog-num-input"></div>
            </td>
          </tr>
        %endif
        % if 'preloaderBackColor' in settings:
          <tr>
            <td>Background Color:</td>
            <td>
              <input type="color" name="preloaderBackColor" value="${settings['preloaderBackColor']}" class="app-settings-color-input">
            </td>
          </tr>
        %endif
        % if 'preloaderDropShadowColor' in settings and 'preloaderDropShadowWidth' in settings:
          <tr>
            <td>Shadow:</td>
            <td>
              <label for="preloaderDropShadowColor" class="app-settings-input-label">Color</label>
              <input type="color" name="preloaderDropShadowColor" value="${settings['preloaderDropShadowColor']}" class="app-settings-color-input">
              <label for="preloaderDropShadowWidth" class="app-settings-input-label">Width</label>
              <div class="pixel-units sameline"><input type="number" name="preloaderDropShadowWidth" value="${settings['preloaderDropShadowWidth']}" min=0 class="dialog-num-input"></div>
            </td>
          </tr>
        %endif
      </table>
    </div>

    <div class="app-settings-ui hidden">
      <table class="app-settings">
        % if 'fullscreenOpenImage' in settings:
          <tr>
            <td>Fullscreen Open:</td>
            <td>
              <label for="fullscreenOpenImageSelector" class="app-settings-img-label">
                <div class="app-settings-img-name">${settings['fullscreenOpenImage'] | filename}</div>
                <div class="app-settings-img-browse"></div>
              </label>
              <input type="file" id="fullscreenOpenImageSelector" accept="image/*" class="hidden">
              <div class="app-settings-img-cont small">
                <img src="${settings['fullscreenOpenImage']}" id="fullscreenOpenImage" class="app-settings-img small">
              </div>
            </td>
          </tr>
        % endif
        % if 'fullscreenCloseImage' in settings:
          <tr>
            <td>Fullscreen Close:</td>
            <td>
              <label for="fullscreenCloseImageSelector" class="app-settings-img-label">
                <div class="app-settings-img-name">${settings['fullscreenCloseImage'] | filename}</div>
                <div class="app-settings-img-browse"></div>
              </label>
              <input type="file" id="fullscreenCloseImageSelector" accept="image/*" class="hidden">
              <div class="app-settings-img-cont small">
                <img src="${settings['fullscreenCloseImage']}" id="fullscreenCloseImage" class="app-settings-img small">
              </div>
            </td>
          </tr>
        % endif
        % if 'moveForwardImage' in settings:
          <tr>
            <td>Move Forward:</td>
            <td>
              <label for="moveForwardImageSelector" class="app-settings-img-label">
                <div class="app-settings-img-name">${settings['moveForwardImage'] | filename}</div>
                <div class="app-settings-img-browse"></div>
              </label>
              <input type="file" id="moveForwardImageSelector" accept="image/*" class="hidden">
              <div class="app-settings-img-cont small">
                <img src="${settings['moveForwardImage']}" id="moveForwardImage" class="app-settings-img small">
              </div>
            </td>
          </tr>
        % endif
      </table>
    </div>

    <div class="app-settings-annotations hidden">
      <table class="app-settings">
        % if 'annotationColor' in settings or 'annotationBackColor' in settings or 'annotationBorderColor' in settings:
          <tr>
            <td>Marker Colors:</td>
            <td>
              % if 'annotationColor' in settings:
                <label for="annotationColor" class="app-settings-input-label">Text</label>
                <input type="color" name="annotationColor" id="annotationColor" value="${settings['annotationColor']}" class="app-settings-color-input">
              % endif
              % if 'annotationBackColor' in settings:
                <label for="annotationBackColor" class="app-settings-input-label">Background</label>
                <input type="color" name="annotationBackColor" id="annotationBackColor" value="${settings['annotationBackColor']}" class="app-settings-color-input">
              % endif
              % if 'annotationBorderColor' in settings:
                <label for="annotationBorderColor" class="app-settings-input-label">Border</label>
                <input type="color" name="annotationBorderColor" id="annotationBorderColor" value="${settings['annotationBorderColor']}" class="app-settings-color-input">
              % endif
            </td>
          </tr>
        % endif
        % if 'annotationFont' in settings:
          <tr>
            <td>Marker Size:</td>
            <td>
              <div class="pixel-units"><input type="number" name="annotationFont" value="${settings['annotationFont']}" min=0 class="dialog-num-input"></div>
            </td>
          </tr>
        % endif
        % if 'annotationDialogColor' in settings or 'annotationDialogBackColor' in settings or 'annotationDialogBorderColor' in settings:
          <tr>
            <td>Dialog Colors:</td>
            <td>
              % if 'annotationDialogColor' in settings:
                <label for="annotationDialogColor" class="app-settings-input-label">Text</label>
                <input type="color" name="annotationDialogColor" id="annotationDialogColor" value="${settings['annotationDialogColor']}" class="app-settings-color-input">
              % endif
              % if 'annotationDialogBackColor' in settings:
                <label for="annotationDialogBackColor" class="app-settings-input-label">Background</label>
                <input type="color" name="annotationDialogBackColor" id="annotationDialogBackColor" value="${settings['annotationDialogBackColor']}" class="app-settings-color-input">
              % endif
              % if 'annotationDialogBorderColor' in settings:
                <label for="annotationDialogBorderColor" class="app-settings-input-label">Border</label>
                <input type="color" name="annotationDialogBorderColor" id="annotationDialogBorderColor" value="${settings['annotationDialogBorderColor']}" class="app-settings-color-input">
              % endif
            </td>
          </tr>
        % endif
      </table>
    </div>

    <div class="app-settings-sharing hidden">
      <table class="app-settings">
        % if 'openGraphTitle' in settings:
          <tr>
            <td>Open Graph Title:</td>
            <td>
              <input type="text" name="openGraphTitle" value="${settings['openGraphTitle']}" class="app-settings-text">
            </td>
          </tr>
        %endif
        % if 'openGraphDescription' in settings:
          <tr>
            <td>Open Graph Description:</td>
            <td>
              <textarea name="openGraphDescription" cols="40" rows="3" class="app-settings-textarea">${settings['openGraphDescription']}</textarea>
            </td>
          </tr>
        %endif
        % if 'openGraphImage' in settings:
          <tr>
            <td>Open Graph Image:<br>1200x630</td>
            <td>
              <label for="openGraphImageSelector" class="app-settings-img-label large">
                <div class="app-settings-img-name">${settings['openGraphImage'] | filename}</div>
                <div class="app-settings-img-browse"></div>
              </label>
              <input type="file" id="openGraphImageSelector" accept="image/*" class="hidden">
              <div class="app-settings-img-cont wide">
                <img src="${settings['openGraphImage']}" id="openGraphImage" class="app-settings-img wide">
              </div>
            </td>
          </tr>
        % endif
        % if 'twitterCard' in settings:
          <tr>
            <td>X/Twitter Image Size:</td>
            <td>
              <select name="twitterCard" class="app-settings-select">
                <option value="summary" ${'selected' if settings['twitterCard'] == 'summary' else ''}>Small</option>
                <option value="summary_large_image" ${'selected' if settings['twitterCard'] == 'summary_large_image' else ''}>Large</option>
              </select>
            </td>
          </tr>
        %endif
      </table>
    </div>

    <div class="app-settings-errors hidden">
      <table class="app-settings">
        % if 'webglErrorMsg' in settings:
          <tr>
            <td>WebGL Error Message:</td>
            <td>
              <textarea name="webglErrorMsg" cols="40" rows="4" class="app-settings-textarea">${settings['webglErrorMsg']}</textarea>
            </td>
          </tr>
        %endif
        % if 'webglErrorImage' in settings:
          <tr>
            <td>WebGL Error Image:</td>
            <td>
              <label for="webglErrorImageSelector" class="app-settings-img-label large">
                <div class="app-settings-img-name">${settings['webglErrorImage'] | filename}</div>
                <div class="app-settings-img-browse"></div>
              </label>
              <input type="file" id="webglErrorImageSelector" accept="image/*" class="hidden">
              <div class="app-settings-img-cont large">
                <img src="${settings['webglErrorImage']}" id="webglErrorImage" class="app-settings-img large">
              </div>
            </td>
          </tr>
        % endif
      </table>
    </div>

    <div class="app-settings-pwa hidden">
      <table class="app-settings">
        % if 'webAppName' in settings:
          <tr class="more-height">
            <td>Progressive Web App:</td>
            <td>
              <div style="width: 380px">
                <input type="checkbox" name="enablePWA" id="enablePWA" value="" ${'checked' if settings['webAppName'] else ''}>
                <label for="enablePWA" class="app-settings-input-label">Enabled</label>
              </div>
            </td>
          </tr>
          <tr ${'class="hidden"' if not settings['webAppName'] else ''}>
            <td>Web App Name:</td>
            <td>
              <input type="text" name="webAppName" value="${settings['webAppName'] if settings['webAppName'] else 'My Awesome App'}" class="app-settings-text">
            </td>
          </tr>
        % endif
        <tr class="more-height">
          <td>Offline Mode:</td>
          <td>
            <input type="checkbox" name="offlinePWA" id="offlinePWA" value="" ${'checked' if settings['offlinePWA'] == 'true' else ''}>
            <label for="offlinePWA" class="app-settings-input-label">Enabled</label>
            <button id="refreshWorkerCache" class="app-settings-button ${'inactive' if settings['offlinePWA'] == 'false' else ''}" ${'disabled' if settings['offlinePWA'] == 'false' else ''}>Refresh Cache</button>
          </td>
        </tr>
      </table>
    </div>
  </form>

  <hr class="app-settings">
  <input type="submit" id="settingsSave" value="Apply Changes" class="button settings-button">
</%block>

<%block name="blkDialogScript">

    diaAppSettingsClose.addEventListener('click', function() {
        destroyDialog('diaAppSettings');
    });

    // preserve settings to compare on send
    const settingsJS = ${json.dumps(settings) | n}

    // HACK: to unquote
    const webglErrorElem = document.querySelector('textarea[name="webglErrorMsg"]');
    if (webglErrorElem) {
        settingsJS['webglErrorMsg'] = webglErrorElem.value;
    }

    const settingsElems = document.querySelectorAll('.settings-left-panel > div');
    const settingsFormParts = document.querySelectorAll('.settings-form > div');
    const settingsHelpURLs = [
        '${utils.genManualURL("introduction/App-Manager.html#app_settings_general_tab")}',
        '${utils.genManualURL("introduction/App-Manager.html#app_settings_preloader_tab")}',
        '${utils.genManualURL("introduction/App-Manager.html#app_settings_ui_tab")}',
        '${utils.genManualURL("introduction/App-Manager.html#app_settings_annotations_tab")}',
        '${utils.genManualURL("introduction/App-Manager.html#app_settings_sharing_tab")}',
        '${utils.genManualURL("introduction/App-Manager.html#app_settings_errors_tab")}',
        '${utils.genManualURL("introduction/App-Manager.html#app_settings_pwa_tab")}'
    ];

    settingsElems.forEach(elem => {
        elem.addEventListener('click', event => {
            for (let i = 0; i < settingsElems.length; i++) {
                if (settingsElems[i] == event.target) {
                    settingsElems[i].classList.add('settings-left-item-active');
                    settingsFormParts[i].classList.remove('hidden');
                    diaAppSettingsHelp.href = settingsHelpURLs[i];
                } else {
                    settingsElems[i].classList.remove('settings-left-item-active');
                    settingsFormParts[i].classList.add('hidden');
                }
            }
        });
    });

    function uploadImage(imageFile, cb) {
        const formData = new FormData();

        formData.append('image', imageFile);
        formData.append('app', "${app['name']}");

        makeRequest('/app_settings/save_image', formData, function(response) {
            cb(response);
        });
    }

    settingsForm.querySelectorAll('input[type="file"]').forEach(function(elem) {
        const labelDiv = elem.previousElementSibling.querySelector('label div');
        const img = elem.nextElementSibling.querySelector('img');

        elem.addEventListener('change', function() {
            uploadImage(elem.files[0], url => {
                labelDiv.innerText = filename(url);
                img.src = url;
            });
        });
    });

    settingsForm.querySelector('input[name="enablePWA"]').addEventListener('change', function(event) {
        const elem = event.target;

        const pwaSettingsLines = Array.from(settingsForm.querySelectorAll('.app-settings-pwa tr')).slice(1,2);
        pwaSettingsLines.forEach(e => {
            if (elem.checked)
                e.classList.remove('hidden');
            else
                e.classList.add('hidden');
        });

    });

    settingsForm.querySelector('input[name="offlinePWA"]').addEventListener('change', function(event) {
        const elem = event.target;
        if (elem.checked) {
            refreshWorkerCache.classList.remove('inactive');
            refreshWorkerCache.disabled = false;
        } else {
            refreshWorkerCache.classList.add('inactive');
            refreshWorkerCache.disabled = true;
        }
    });

    function requestWorkerUpdate(cb=()=>{}) {
        makeRequest('/app_settings/update_worker?app=${app["name"] | u}', null, function(response) {
            if (response != 'ok')
                console.error('Failed to update service worker cache');
            cb(response);
        });
    }

    refreshWorkerCache.addEventListener('click', (event) => {
        requestWorkerUpdate();
        event.preventDefault();
    });

    settingsSave.addEventListener('click', function(event) {

        const data = {};

        settingsForm.querySelectorAll('input').forEach(function(elem) {
            switch (elem.name) {
            case 'preloaderBarType':
            case 'enablePWA':
                // pass
            break;
            case 'preloaderBarSolidColor':
                if (elem.parentElement.querySelector('input[type="radio"]').checked)
                    data['preloaderBarCSSColor'] = elem.value;
                break;
            case 'preloaderBarGradientColor':
                if (elem.parentElement.querySelector('input[type="radio"]').checked)
                    data['preloaderBarCSSColor'] = 'linear-gradient(90deg, C1, C2)'.replace('C1', elem.value);
                break;
            case 'preloaderBarGradientColor2':
                if (elem.parentElement.querySelector('input[type="radio"]').checked)
                    data['preloaderBarCSSColor'] = data['preloaderBarCSSColor'].replace('C2', elem.value);
                break;
            case 'preloaderBarCSSColor':
                if (elem.parentElement.querySelector('input[type="radio"]').checked)
                    data['preloaderBarCSSColor'] = elem.value;
                break;
            case 'webAppName':
                if (settingsForm.querySelector('input[name="enablePWA"]').checked)
                    data['webAppName'] = elem.value;
                else
                    data['webAppName'] = '';
                break;
            break;
            default:
                switch (elem.type) {
                    case 'checkbox':
                        data[elem.name] = elem.checked ? 'true' : 'false';
                        break;
                    case 'text':
                    case 'hidden':
                    case 'color':
                        data[elem.name] = elem.value;
                        break;
                    case 'number':
                        data[elem.name] = Number(elem.value);
                        break;
                }
                break;
            }
        });

        settingsForm.querySelectorAll('textarea').forEach(function(elem) {
            data[elem.name] = elem.value;
        });

        settingsForm.querySelectorAll('input[type="file"]').forEach(function(elem) {
            const img = elem.nextElementSibling.querySelector('img');
            data[img.id] = img.getAttribute('src');
        });

        settingsForm.querySelectorAll('select').forEach(function(elem) {
            elem.querySelectorAll('option').forEach(function(elemOpt) {
                if (elemOpt.selected)
                    data[elem.name] = elemOpt.value;
            });
        });

        // do not send unmodified data
        for (const s in data) {
            if (data[s] == settingsJS[s])
                delete data[s];
        }

        const jsonData = JSON.stringify(data);

        makeRequest('/app_settings/save', jsonData, function(response) {
            // request worker update for offline mode (enabled before)
            if (!('offlinePWA' in data) && settingsJS['offlinePWA'] == 'true') {
                requestWorkerUpdate();
            }

            destroyDialog('diaAppSettings');
        });

        event.preventDefault();
    });

</%block>
