{% extends 'base.html' %}

{% block title %}Reading &quot;{{ html_title }}&quot;{% endblock %}

{% block body %}

<script type="text/javascript" src="{{ url_for('static', filename='js/player.js') }}" charset="utf-8" defer></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/resize.js') }}" charset="utf-8" defer></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/text-options.js') }}" charset="utf-8" defer></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/dict-tabs.js') }}" charset="utf-8"></script>

<div id="rendering_controls" style="display: none">
  <pre>
    lang_is_rtl: <input id="lang_is_rtl" value="{{ is_rtl }}">
    book_id: <input id="book_id" value="{{ book.id }}">
    book_audio: <input id="book_audio_file" value="{{ book.audio_filename or '' }}">
    book_audio_current_pos: <input id="book_audio_current_pos" value="{{ book.audio_current_pos or 0 }}">
    book_audio_bookmarks: <input id="book_audio_bookmarks" value="{{ book.audio_bookmarks or '' }}">
    page_num: <input id="page_num" value="{{ page_num }}">
    page_count: <input id="page_count" value="{{ page_count }}">
    highlights: <span id="show_highlights">{{ show_highlights|lower }}</span>
  </pre>
</div>

<script>
  // The sentence dictionaries configured for the language.  This var
  // is used in lute.js.
  var LUTE_SENTENCE_LOOKUP_URIS = {{ sentence_dict_uris|safe }};
</script>


<div id="read_pane_container">

<div id="read_pane_left">

  <div id="reading_menu">
    {% include "read/reading_menu.html" %}
  </div>

  <div id="reading-header">

    <div class="reading_header_container">
        <div class="reading_header_left">
          <div class="hamburger-btn" onclick="toggleMenu()">
            <span class="hamburger"></span>
            <span class="hamburger"></span>
            <span class="hamburger"></span>
          </div>
	  <a href="/">
		<img
		  src="{{ url_for('static', filename='img/lute.png') }}"
		  class="lutelogo_small"
		  style="cursor: pointer"
		  title="Home"
		/>
	  </a>
        </div>
        <div class="reading_header_mid">
        <div class="reading_header_mid_top">
          <div class="texttitlecontainer">
            <h1 id="headertexttitle" {% if is_rtl %}dir="rtl" {% endif %} class="hide">{{ book.title }}</h1>
          </div>
          <div class="reading_header_page">
            <!-- <a id="reading_home_link" class="home-link" href="/">Home</a> -->
            <div class="read-bookmark-buttons-container">
              <button id="read-bkm-save-btn" class="read-bkm-btn"></button>
              <!-- <div class="read-bookmark-jump-container"> -->
                <!-- <button id="read-bkm-prev-btn" class="read-bkm-btn"></button> -->
                <!-- <button id="read-bkm-next-btn" class="read-bkm-btn"></button> -->
              <!-- </div> -->
            </div>
            <div id="page_indicator">{{ page_num }}/{{ page_count }}</div>
          </div>
          </div>
          <div class="read-slide-container">
            <div class="read_page_nav read_page_disabled"
              id="navPrev"
              onclick="goto_relative_page(-1)">◀</div>
            <input type="range" id="read-slider" class="read_page_disabled" max="{{ page_count - 1 }}" value="{{ page_num }}" step="1">
            <div class="read_page_nav read_page_disabled"
              id="navNext"
              onclick="goto_relative_page(1)">▶</div>
          </div>
        </div>
    </div>

    <!-- <div class="definition-container"></div> -->

  </div>

  {% include "read/audio_player.html" %}

  <h1 id="thetexttitle" {% if is_rtl %}dir="rtl" {% endif %} class="hide">{{ book.title }}</h1>
  <div id="thetext" {% if is_rtl %}dir="rtl" {% endif %}>
    ...
  </div>

  <div id="reading-footer" style="text-align: center">
    <p>
      <span
        id="footerMarkRestAsKnownNextPage"
        style="cursor: pointer; color: #4CBB17;"
        onclick="handle_page_done(true, 1)"
        title="Mark rest as known, mark page as read, then go to next page">
        &#x2714;
      </span>

      <span
        id="footerNextPage"
        style="cursor: pointer; font-size: 1.5em; font-weight: bold;"
        onclick="handle_page_done(false, 1)"
        title="Mark page as read, then go to next page">
        &#8250;
      </span>
    </p>

    <div id="final_page_controls" class="hide">
      <p>
        <span
          id="footerMarkRestAsKnown"
          style="cursor: pointer; color: #4CBB17;"
          onclick="handle_page_done(true, 0)"
          title="Mark rest as known, mark page as read">
          &#x2714;
        </span>

        <span
          id="footerDone"
          style="cursor: pointer;"
          onclick="handle_page_done(false, 0)"
          title="Mark page as read">
          &#x2714;
        </span>
      </p>

      <h2>&#127881;</h2>
      <p>
        <a
          href=""
          tabindex="-1"
          onclick="$('#actionposter').submit(); return false;"
          >Archive book</a>
        |
        <a href="/" tabindex="-1">Home</a>
      </p>

      <form
        id="actionposter"
        method="post"
        action="/book/archive/{{ book.id }}"
        ></form>
    </div>

  </div>
  <div class="btm-margin-container"></div>
</div>

<div id="read_pane_right">
  <button class="close-btn read-pane-right-close-btn" onclick="closeRightPane()"></button>
  <div class="wordframecontainer">
  <iframe
    name="wordframe"
    id="wordframeid"
    class="rightreadingframe"
    src="about:blank"
    scrolling="auto"
    style="height: 35%; width: 100%"
    frameborder="0"
  >
    Frame support required.
  </iframe>
  </div>
  <div class="dictcontainer">
    <div id="dicttabs">
      <div id="dicttabslayout"></div>
      <div id="dicttabsstatic"></div>
    </div>
    <div id="dictframes"></div>
  </div>
</div>

</div>

<script>
  LookupButton.LANG_ID = {{ lang_id | safe }};
  LookupButton.TERM_DICTS = {{ term_dicts | safe }};

  let mouseY;
  let scrollY;
  let scrollYBeforeReload;
  const mediaTablet = window.matchMedia("(max-width: 980px)");
  const readPaneRight = document.getElementById("read_pane_right");
  const btmMarginCont = document.querySelector(".btm-margin-container");
  const theText = document.getElementById("thetext");
  const focusChk = document.getElementById("focus");

  // fixes the "bug" where if right pane is opened in mobile view and after the screen is resized up,
  // right pane doesn't translate up to 0 because of inline transform property
  // this one is not super important
  // because the mobile size won't be resized to a desktop size in a real use case
  mediaTablet.addEventListener("change", function() {
    if (!mediaTablet.matches) {
      readPaneRight.style.removeProperty("transform");
    }
  })

  // This must be "pointerup", and not "click", to properly display
  // the term form when a multi-word term is created on mobile,
  // because the "touchend" event cancels the click event.
  document.addEventListener("pointerup", (event) => {
      mouseY = event.clientY;
      scrollY = window.scrollY;
  });

  window.addEventListener("scrollend", function(e) {
    scrollYBeforeReload = window.scrollY;
  });

  focusChk.addEventListener("change", () => {
    const book_id = $('#book_id').val();
    readPaneContainer.classList.toggle("focus-mode-active");
    localStorage.setItem(`focusMode-book${book_id}`, `${focusChk.checked}`)
  })

  $(document).ready(function () {
    const theTextReloadObs = new MutationObserver((mutationList, observer) => {
      if (scrollYBeforeReload) window.scrollTo(0, scrollYBeforeReload);
    });
    
    theTextReloadObs.observe(theText, {childList: true, subtree: true});

    // do not load focus state if in tablet mode
    if (!mediaTablet.matches) {
      const book_id = $('#book_id').val();
      const focusVal = localStorage.getItem(`focusMode-book${book_id}`);
      if (focusVal === "true") {
        readPaneContainer.classList.add("focus-mode-active");
        focusChk.checked = true;
      }
    }
    
    createLookupButtons();

    window.addEventListener("message", function(event) {
      if (event.data.event === "LuteTermFormOpened") {
        LookupButton.TERM_FORM_CONTAINER = wordFrame.contentDocument.getElementById("term-form-container");
        loadDictionaries();
      }

      // When term form posts data (either updating or deleting terms),
      // reload the full reading screen.
      if (event.data.event === "LuteTermFormPosted") {
        const bookid = $('#book_id').val();
        const pagenum = $('#page_num').val();
        const url = `/read/renderpage/${bookid}/${pagenum}`;
        const marked = $('.kwordmarked');
        let marked_id = "nomatches"
        if (marked.length != 0) {
          marked_id = $(marked[0]).attr('id');
        }

        // Force remove the old popup.
        // ref https://stackoverflow.com/questions/19266886/
        //   tooltip-not-disappearing
        $('div.ui-tooltip').remove();

        $(".dictcontainer").css('display', 'none');

        $('#thetext').load(url, function() {
          const re_marked = $(`#${marked_id}`);
          re_marked.removeClass('kwordmarked');
          re_marked.addClass('wordhover');
        });
      };

    });

    if (have_audio_file()) {
      // Don't actually load the source -- for some reason,
      // the ajax page load was causing the audio src to
      // only load occasionally!  Not sure why.  Source loading
      // is handled in load_player_source().
      $('div.audio-player-container').show();
    }
    goto_relative_page(0, true);

    // If the css slide-in menu is open, clicking away from it closes the menu.
    $(document).click(function(event) {
      const menu = document.getElementById("reading_menu");
      // const menuBtn = document.querySelector(".hamburger-btn");
      const menu_clicked = event.target.closest("#reading_menu");
      const menuBtn_clicked = event.target.closest(".hamburger-btn");
      const rightPaneClicked = event.target.closest("#read_pane_right");
      // if (event.target != menuBtn || event.target.parentNode != menuBtn) 
      if(!menu_clicked && !menuBtn_clicked)
        menu.classList.remove("open-menu");

      // close rightPane if it's not click, it's children not clicked or a word is not clicked
      if(!rightPaneClicked && event.target.parentNode != readPaneRight && !event.target.classList.contains("textitem")) {
          closeRightPane();
        }
    });
  });

  // mobile view
  window.addEventListener("message", function(event) {
    if (event.data.event === "LuteTermFormOpened" && mediaTablet.matches) {
        const viewportHeight = document.documentElement.clientHeight;
        const mousePosPercent = mouseY / viewportHeight * 100;
        // move the rightPane to the mouse position + some offset
        readPaneRight.classList.add("open-dict");
        btmMarginCont.classList.add("open-dict");
        document.querySelector("#read_pane_right.open-dict").style.transform = `translateY(${Math.round(mousePosPercent) + 10}%)`;
        readPaneRight.style.opacity = "1";
        // add margin to the bottom of readLeft so it's fully scrollable to the bottom when the dict is over text
        document.querySelector(".open-dict.btm-margin-container").style.marginTop = `calc(${viewportHeight - mouseY + 70}px - var(--player-height))`;
        // sometimes there's an unnecessary text scroll when clicking on a word. return to the previous scroll position
        window.scrollTo(0, scrollY);
    }
  });

  let have_audio_file = function() {
    return ($('#book_audio_file').val() != '');
  }

  /**
   * Actually set the player source, loading the file,
   * and load all bookmarks etc.
   */
  let load_player_source = function() {
    const book_id = $('#book_id').val();
    // console.log('setting source to ' + `/useraudio/stream/${book_id}`);
    player.src = `/useraudio/stream/${book_id}`;

    t = parseFloat($('#book_audio_current_pos').val());
    player.currentTime = t;
    timeline.value = t;

    bookmarksArray = [];
    bkstring = $('#book_audio_bookmarks').val();
    bks = [];
    if (bkstring != "")
      bks = bkstring.split(';').map((b) => parseFloat(b));
    for (b of bks) {
      bookmarksArray.push(b);
    }

    start_player_post_loop();
  };

  // Set "page X/Y" in page nav.
  let set_page_fraction = function() {
    const pagenum = parseInt($('#page_num').val());
    const maxpage = parseInt($('#page_count').val());
    $('#page_indicator').text(`${pagenum}/${maxpage}`);
  };

  // Enable page nav links, depending on page num.
  let enable_page_nav_links = function() {
    const pagenum = parseInt($('#page_num').val());
    const maxpage = parseInt($('#page_count').val());
    if (pagenum > 1) {
      $('#navPrev').removeClass('read_page_disabled');
    }
    else {
      $('#navPrev').addClass('read_page_disabled');
    }
    if (pagenum < maxpage) {
      $('#navNext').removeClass('read_page_disabled');
    }
    else {
      $('#navNext').addClass('read_page_disabled');
    }
    //toggleSliderStatus();
  };


  // Show/hide footer controls.
  let set_footer_control_visibility = function() {
    const pagenum = parseInt($('#page_num').val());
    const maxpage = parseInt($('#page_count').val());
    if (pagenum == maxpage) {
      $('#final_page_controls').removeClass("hide");
      $('#footerMarkRestAsKnownNextPage').addClass("hide");
      $('#footerNextPage').addClass("hide");
    }
    else {
      $('#final_page_controls').addClass("hide");
      $('#footerMarkRestAsKnownNextPage').removeClass("hide");
      $('#footerNextPage').removeClass("hide");
    }
  };


  let show_hide_title = function(p) {
    const t = $('#thetexttitle');
    const h = $('#headertexttitle');
    if (p == 1) {
      t.removeClass('hide');
      h.addClass('hide');
    }
    else {
      t.addClass('hide');
      h.removeClass('hide');
    }
  };

  // for the reading page return the main container to full width
  document.querySelector(".container").style.cssText = `width: 100%; margin: 0;`;
  
  const readSlider = document.getElementById("read-slider");
  const maxpage = parseInt($('#page_count').val());
  // disable read slider if there's only 1 page
  if (maxpage > 1) document.getElementById("read-slider").classList.remove("read_page_disabled");

  readSlider.addEventListener("input", function() {
    const pagenum = parseInt($('#page_num').val());
    const p = Number(readSlider.value) + 1 - pagenum;
    const actualPage = getActualPage(p);
    updateReadSlider(actualPage);
    document.getElementById("page_indicator").textContent = `${actualPage}/${maxpage}`;
  })
  
  readSlider.addEventListener("change", function() { 
    const pagenum = parseInt($('#page_num').val());
    const p = Number(readSlider.value) + 1 - pagenum;
    goto_relative_page(p);
  })

  function updateReadSlider(p) {
    readSlider.value = p - 1;
    readSlider.style.backgroundSize = `${100 / (maxpage - 1) * readSlider.value}% 100%`;
  }
  
  function getActualPage(p) {
    const pagenum = parseInt($('#page_num').val());
    let actualPage = pagenum + p;
    if (actualPage < 1)
      actualPage = 1;
    if (actualPage > maxpage)
      actualPage = maxpage;

    return actualPage;
}
/**
 * Go to page relative to that stored in page_num input.
 *
 * On first load of page, initial_page_load is set to true.
 *
 * It appears that for Firefox the player source can't be set
 * while the page content is being ajax'd in.  This makes
 * _NO SENSE AT ALL_ but moving the player source loading
 * to the ajax "success" function worked.  ???
 */
  function goto_relative_page(p, initial_page_load = false) {
    const bookid = $('#book_id').val();
    const actualPage = getActualPage(p);

    updateReadSlider(actualPage);

    const url = `/read/renderpage/${bookid}/${actualPage}`;
    $.get(
      url,
      function(data, status) {
        $('#thetext').html(data);
        add_status_classes();
        reset_cursor();
        start_hover_mode(false);
        $('#page_num').val(actualPage);
        enable_page_nav_links();
        set_page_fraction();
        set_footer_control_visibility();
        show_hide_title(actualPage);
        $("html, body").animate({ scrollTop: 0 });

        if (initial_page_load) {
          prepareTextInteractions();
        }

        // Magic hack for player source to load consistently
        // in Firefox.
        if (initial_page_load && have_audio_file()) {
          load_player_source();
        }
      }
    );
  }

  function closeMenu() {
    const menu = document.getElementById("reading_menu");
    menu.classList.remove("open-menu");
  }

  function toggleMenu() {
    const menu = document.getElementById("reading_menu");
    menu.classList.toggle("open-menu");
  }

  function closeRightPane() {
      readPaneRight.classList.remove("open-dict");
      btmMarginCont.classList.remove("open-dict");
      btmMarginCont.style.removeProperty("margin-top");
      readPaneRight.style.removeProperty("transform");
      readPaneRight.style.removeProperty("opacity");
  }

  function edit_current_page() {
    const bookid = $('#book_id').val();
    const pagenum = parseInt($('#page_num').val());
    location.href = `/read/editpage/${bookid}/${pagenum}`;
  }

  // Handle green checkmark in footer.
  function handle_page_done(mark_rest_known = false, next_relative_page = 0) {
    const bookid = $('#book_id').val();
    const pagenum = parseInt($('#page_num').val());
    data = {
      bookid: bookid,
      pagenum: pagenum,
      restknown: mark_rest_known
    };
    $.ajax({
      type: 'post',
      url: '/read/page_done',
      data: JSON.stringify(data),
      contentType: "application/json; charset=utf-8"
    }).done(function(d) {
      goto_relative_page(next_relative_page);
    });
  }

  function add_bookmark() {
    const book_id = document.querySelector('#book_id')?.value;
    const page_num = document.querySelector('#page_num')?.value;
    let title = prompt(`Enter bookmark title, or Cancel to quit`);

    if (!title)
      return;

    fetch(`/bookmarks/add`, {
      method: "POST",
      cache: "no-cache",
      credentials: "same-origin",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        title: title,
        book_id: book_id,
        page_num: page_num,
      })
    }).then((resp) => resp.json()).then(json => {
      if (json?.success === true) {
        alert(`Bookmark "${title}" added.`)
      } else {
        alert(`Unable to add bookmark. ${json?.reason || "Unknown reason"}`)
      }
    })
  }

</script>

{% endblock %}
