<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="icon" type="image/png" sizes="96x96" href="/assets/favicon/favicon-96x96.png">
  <meta property="og:image" content="/assets/favicon/favicon-96x96.png">
  <title>IMPERIAL</title>
  <meta name="description" content="IMPERIAL is a code/text storing site where you can share, edit, or encrypt documents with integrations such as Discord and GitHub Gists. ">
  <meta name="keywords"
    content="Imperial, Imperialb, Imperialbin, imperialb.in, hastebin, bin, paste, instant delete pastes, document sharing, code sharing, visual studio code, vsce, vsc, vs, visual studio, code, developer, developers, dev, devlooskie, looskie, looskieee, IMPERIAL, paste your document, paste, your, document, editor, invite only, invite, api, restful api, json api, discord">
  <link rel="stylesheet" href="/assets/css/reallyGlobal.css?cum=fgedswwergewrggwefr">
  <link rel="stylesheet" href="https://unpkg.com/tippy.js@6.2.7/animations/shift-away.css?cum=fgedswgwefr" />
  <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500&display=swap" rel="stylesheet">
  <script src="https://kit.fontawesome.com/ec3f0c8487.js?cum=fgedswgwefrwerg" crossorigin="anonymous"></script>
  <script src="https://unpkg.com/@popperjs/core@2?cum=fgedswergwgwefr"></script>
  <script src="https://unpkg.com/tippy.js@6?cum=fgedswgergwefr"></script>
</head>


<body>
  <div class="pasteSettings" id="addUser">
    <div class="pasteContainer">
      <h1>Add users to allow edit access</h1>
      <span id="editor-error"></span><br>
      <input id="user" type="text" autocomplete="off" placeholder="Add a user here">
      <button class="addUserBtn" onclick="addUser(document.getElementById('user').value)">Add user</button>
      <ul id="editorArray" class="editorArray"></ul>
      <br><button id="cancel-settings" class="cancelSettings" onclick="clearUsers()">Cancel and clear</button>
      <button onclick="closeAddUser()">Save</button>
      <br><br>
    </div>
  </div>
  <div class="pasteSettings" id="setLanguage">
    <div class="pasteContainer" id="putMarginOnThisPlease">
      <h1 id="selectLanguage">Select a language</h1>
      <button class="customStupidXButton tooltip" data-tippy-content="Close window (esc)"
        onclick="closeLanguageSelector()"><i class="far fa-times-circle"></i></button>
      <input type="text" class="searchBar" id="searchBarTings"
        oninput="searchResults(document.getElementById('searchBarTings').value)" placeholder="Search" autocomplete="off" autofocus>
      <ul class="languageList" id="languageList">
      </ul>
      <br>
      <button class="closeBtn" onclick="closeLanguageSelector()">Close</button>
      <br><br>
    </div>
  </div>
  <% if( loggedIn ) {%>
  <div class="menu">
    <div class="settings" id="accountDrop" style="display: none;">
      <ul class="account">
        <li class="setting" onclick="location.href='/account'">User settings</li>
        <li class="setting" onclick="location.href='/account#documentSettings'">Doc. settings</li>
        <li class="setting" id="discord" onclick="window.open('https://imperialb.in/dsc', '_blank')">
          Discord</li>
        <div class="dumbLine"></div>
        <% if (isAdmin) { %>
          <li class="setting" onclick="location.href='/admin'">Admin panel</li>
        <% } %>
        <li class="setting" id="logoutBtn" onclick="location.href = '/logout?_method=DELETE'">Logout
        </li>
      </ul>
    </div>
    <div class="menu-content">
      <h6>IMPERIAL</h6>
      <ul>
        <li id="changeLanguage" class="tooltip" data-tippy-content="Change language"><button id="icon"
            class="changeLanguageBtn" onclick="openLanguageSelector()"><i class="fas fa-minus"></i></button>
        </li>
        <li id="users" class="addEditors tooltip" data-tippy-content="Add users"><button id="icon"
            onclick="toggleAddUser()"><i class="fas fa-user-friends"></i></button></li>
        <li id="save" class="save tooltip" data-tippy-content="Save document"> <button id="icon"
            onclick="createDocument()"><i class="far fa-save fa-lg"></i></button>
        </li>
        <li id="new" class="new tooltip" data-tippy-content="New document"> <button id="icon" onclick="newDocument()"><i
              class="fas fa-file-alt fa-lg"></i></button> </li>
        <li id="account"> <img src="<%= pfp %>" alt="Profile picture" class="pfp" draggable="false">
        </li>
      </ul>
    </div>
    <ul id="messages"></ul>
  </div>
  <% } else { %>
  <div class="menu">
    <div class="settings" id="accountDrop" style="display: none;"></div>
    <div class="menu-content">
      <h6>IMPERIAL</h6>
      <ul>
        <li id="changeLanguage" class="tooltip" data-tippy-content="Change language"><button id="icon"
            class="changeLanguageBtn" onclick="openLanguageSelector()"><i class="fas fa-minus"></i></button>
        </li>
        <li id="save" class="save tooltip" data-tippy-content="Save document"> <button id="icon"
            onclick="createDocument()"><i class="far fa-save fa-lg"></i></button>
        </li>
        <li id="new" class="new tooltip" data-tippy-content="New document"> <button id="icon" onclick="newDocument()"><i
              class="fas fa-file-alt fa-lg"></i><br></button>
        </li>
        <li class="loginBtn"> <button id="login" onclick="location.href='/login'">Login</button> </li>
        <li> <button id="signup" onclick="location.href='/register'">Signup</button> </li>
        <li id="account"> <img src="/assets/img/pfp.png" alt="Profile picture" class="pfp" draggable="false"
            style="display: none"> </li>
      </ul>
    </div>
    <ul id="messages"></ul>
  </div>
  <% }%>
  <div id="codeThing" class="editor" onkeydown="saveText()"></div>
  <script src="/assets/js/main.js?cum=fgedswgwefr"></script>
  <script src="/assets/js/highlight.js?cum=fgedswgwefr"></script>
  <script src="/assets/js/src-min-noconflict/ace.js?cum=fgedswgwefr"></script>
  <script>
    // Automatically detect the language
    const getThisStupidThing = localStorage.getItem('language');

    if (!getThisStupidThing) localStorage.setItem('language', 'auto')
    if (getThisStupidThing && getThisStupidThing !== 'auto')
      document.querySelector('.changeLanguageBtn').textContent = localStorage.getItem('language');

    let language;
    setInterval(() => {
      if (localStorage.getItem('language') === 'auto') {
        const checkEditor = window.editor.getValue();
        if (checkEditor.length > 0) {
          const autoLanguage = hljs.highlightAuto(window.editor.getValue())
          const btn = document.querySelector('.changeLanguageBtn');

          if (language === autoLanguage.language) return; // Check if the language is the same as last time.
          if (autoLanguage.relevance < 5) return language = 'none'; // If language relevance is low, dont bother to set it.
          btn.textContent = autoLanguage.language;
          language = autoLanguage.language;

          // Set language to editor
          window.editor.session.setMode(`ace/mode/${language.toLowerCase()}`)
        }
      }
    }, 500)

    const saveText = () => localStorage.setItem('saveText', window.editor.getValue())

    const restoreSession = () => {
      window.editor.setValue(localStorage.getItem('saveText'))
      localStorage.removeItem('saveText');
      document.getElementById('restoreSes').remove()
    }

    // Some consts we need
    const template = document.getElementById('accountDrop');
    tippy('#account', {
      content: template.innerHTML,
      allowHTML: true,
      trigger: 'click',
      placement: 'bottom',
      animation: 'shift-away',
      interactive: true,
    });
    tippy('.tooltip', {
      arrow: false,
      animation: 'shift-away',
      placement: 'bottom'
    })
    const loggedIn = JSON.parse('<%= loggedIn %>')
    const settings = {
      clipboard: loggedIn ? JSON.parse('<%= settings.clipboard %>') : false,
      longerUrls: loggedIn ? JSON.parse('<%= settings.longerUrls %>') : false,
      instantDelete: loggedIn ? JSON.parse('<%= settings.instantDelete %>') : false,
      encrypted: loggedIn ? JSON.parse('<%= settings.encrypted %>') : false,
      expiration: loggedIn ? JSON.parse('<%= settings.expiration %>') : 5,
      imageEmbed: loggedIn ? JSON.parse('<%= settings.imageEmbed %>') : false,
    }

    const languageStorage = localStorage.getItem('language');

    window.editor = ace.edit("codeThing");
    editor.setOptions({
      showPrintMargin: false,
      fontSize: '14.5px',
    });
    editor.session.setUseWrapMode(true)
    editor.session.setMode(languageStorage && languageStorage !== "auto" ? `ace/mode/${languageStorage}` : "ace/mode/plain_text");

    (() => {
      const duplicate = localStorage.getItem("duplicateDocument");
      if (duplicate) {
        localStorage.removeItem('duplicateDocument')
        return window.editor.session.setValue(duplicate)
      }

      navigator.clipboard
        .readText()
        .then((copiedText) => {
          if (settings.clipboard) {
            const restore = localStorage.getItem('saveText');
            window.editor.session.setValue(copiedText);
            if (restore && restore.length > 0 && copiedText !== restore) {
              const messages = document.getElementById('messages');
              messages.innerHTML += '<li class="message info clickableMsg" onclick="restoreSession()" id="restoreSes"><i class="fas fa-question" style="padding-right: 9px;"></i> Restore last session?</li>'
            }
            editor.focus()
            editor.navigateFileEnd();
          }
        })
        .catch((err) => {
          console.log(err)
          console.log("denied paste capabilities");
        });
    })()

    async function createDocument() {
      if (window.editor.getValue() == 0) return console.log("you gotta put sum in b");
      const editorArray = JSON.parse(localStorage.getItem('editorArray'))
      let editors = editorArray ? editorArray.map((user) => user.username) : []


      const options = {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          code: window.editor.getValue().toString(),
          language: window.editor.session.$modeId.replace('ace/mode/', ''),
          longerUrls: settings.longerUrls,
          imageEmbed: settings.imageEmbed,
          expiration: settings.expiration,
          instantDelete: settings.instantDelete,
          encrypted: settings.encrypted,
          editors: editors
        })
      }
      fetch("/api/document", options)
        .then(async res => {
          const messages = document.getElementById('messages');

          if(res.status === 413) return messages.innerHTML += `<li class="message error"><i class="fas fa-times" style="padding-right: 9px;"></i> Text too large!</li>`
          
          const documentRes = await res.json();

          localStorage.removeItem('saveText');
          if (documentRes.document.instantDelete || documentRes.document.encrypted) {
            let urlToCopy;
            if (documentRes.document.encrypted) {
              console.log(documentRes.document);
              urlToCopy = `/p/${documentRes.document.documentId}?password=${documentRes.document.password}`
              window.history.pushState({}, null, urlToCopy);
              messages.innerHTML += `<li class="message success"><i class="fas fa-check" style="padding-right: 9px;"></i> Copied password!</li>`
            } else {
              urlToCopy = `/p/${documentRes.document.documentId}`
              window.history.pushState({}, null, urlToCopy);
              messages.innerHTML += `<li class="message success"><i class="fas fa-check" style="padding-right: 9px;"></i> Copied URL!</li>`
            }
            return copy(`${location.href}`)
          }

          localStorage.removeItem('editors')
          location.href = `/p/${documentRes.document.documentId}?copy=true`
        })
        .catch(err => {
          console.log(err);
        });
    }

    function copy(thingToCopy) {
      const linkBox = document.createElement("textarea");
      linkBox.value = thingToCopy
      document.body.appendChild(linkBox);
      linkBox.select();
      document.execCommand("copy");
      document.body.removeChild(linkBox);
    }
  </script>
</body>

</html>