/*
 *
 * Premint Checker
 *
 * @authoer MePunk Wake
 * @created 2022/04/17
 * @updated 2022/04/29
 * @version 1.3.1
 *
 */
(function ($) {

  if (! $)
    return reject_usage ();


  /*
   *
   * Current version
   *
   */
  const VERSION = "1.3.1";
  const LAST_VERSION = window.pc_last_version || false;
  const ENABLE_VERSION_CHECKER = true;


  /*
   *
   * Defines
   *
   */
  const LAB = {
    host: "lab.mepunk.tech",
    path: "/tool/utility/premint",
    vurl: "/p/tool/utility/premint/version.txt?" + (new Date ()).getTime ()
  };

  const PREMINT = {
    host: "www.premint.xyz",
    path: "/collectors/entries/",
    delay: 300,
    amount: 300
  };


  /*
   *
   * Main function
   *
   */
  function main () {


    /*
     *
     * Premint process flow
     *
     */
    if (is_premint (location) && check_jquery_exists ($)) {

      let idx = 0
        , $cards = $(".card")
        , end = Math.min (PREMINT.amount, $cards.not (".loaded").length) - 1;

      ENABLE_VERSION_CHECKER && check_last_version ();
      generate_style ();
      generate_url ($cards.not (".urled"));
      queue_retrieve ($cards.not (".loaded"), idx, end);

      return;
    }


    /*
     *
     * Lab process flow
     *
     */
    else if (is_lab (location) && check_jquery_exists ($)) {
    }

    reject_usage ();

    return;
  }


  /*
   *
   * Alert if not avialable
   *
   */
  function reject_usage () {

    if (confirm ("此工具只能在下列網址使用,是否跳轉至該網址?\nhttps://www.premint.xyz/collectors/entries/"))
      location.href = "https://www.premint.xyz/collectors/entries/";

    return false;
  }


  /*
   *
   * Check if at url: https://lab.mepunk.tech/tool/utility/premint
   *
   */
  function is_lab (location) {
    return (location.host === LAB.host && location.pathname === LAB.path);
  }


  /*
   *
   * Check if at url: https://www.premint.xyz/collectors/entries/
   *
   */
  function is_premint (location) {
    return (location.host === PREMINT.host && location.pathname === PREMINT.path);
  }


  /*
   *
   * Check if jQuery library exists
   *
   */
  function check_jquery_exists (jq) {
    return ! (typeof jq == "undefined");
  }


  /*
   *
   * Check current page verison
   *
   */
  function check_current_page_version () {
  }


  /*
   *
   * Check current page verison
   *
   */
  function get_filtered_verify_html (html) {

    html = html.substring (html.indexOf (`<div class="card-body `));
    html = html.substring (0, html.indexOf (`<form method="get" `));

    return $(html).find ("p").remove ().end ().eq (0);
  }


  /*
   *
   * Check current page verison
   *
   */
  function get_filtered_result_html (html, selector = "") {

    html = html.substring (html.indexOf (`<form role="form" `));
    html = html.substring (0, html.indexOf (`</form>`));
    html = html.replaceAll ("fa-3x", "").replaceAll ("heading-3", "");

    if (selector == "")
      return $(html);

    return $(html).find (selector).eq (0);
  }


  /*
   *
   * Generate urls
   *
   */
  function check_last_version () {

    if (LAST_VERSION !== false)
      return;

    $.get (`https://${LAB.host}${LAB.vurl}`)
      .done (function (ver) {

        ver = ver.replace ("\n", "").replace ("\r", "");

        window.pc_last_version = ver;

        if (ver <= VERSION)
          return;

        $("body").append (`<a href="https://${LAB.host}${LAB.path}"`
          + ` target="_blank"`
          + ` class="fixed-top px-3 py-2 bg-success text-white m-3 rounded text-center"`
          + ` style="width: 215px; font-size: 14px; left: initial; right: 0; text-decoration: underline;">`
          + `Premint Checker v${ver} <i class="fas fa-external-link pl-2"></i></a>`);
      });
  }


  /*
   *
   * Generate urls
   *
   */
  function generate_style () {

    if ($("body").find ("pchecker-style").length > 0)
      return;

    $("body").append ("<style id=\"pchecker-style\">.col-lg-3.mb-4{width:33%;min-width:33%}.card{flex-direction:row;height:100%;overflow:hidden}.card-image{width:80px;min-width:80px;height:100%}.card-image img{object-fit:cover;height:100%}.card-body{padding:0}.card-body.text-truncate{display:flex;flex-direction:column;justify-content:space-between}.card-info{padding:7px 12px}.card-info a{white-space:initial}.card-body .loading{display:inline-block;position:relative;left:2px;bottom:-2px;color:#aaa}.card-body .error-message{margin-left:-.5px;margin-top:5px}.card-body .error-message .message{margin-left:1.5px}.card-verify{display:flex;align-items:center;padding:7px 0;white-space:initial;border-top:1px solid #e0e1e2}.card .border-bottom{border-color:#eaeaea!important}.card-verify .heading{font-size:22px!important;padding:0 8px 0 10px;margin:0}.card-verify .heading-3{padding:5px 0;text-align:left;font-size:14px!important}.card-result{padding:7px 12px;position:relative}.card-result i:first-child{position:absolute;top:10px;left:10px}.card-result .heading{display:inline-block;padding-left:20px;white-space:initial;font-size:14px}.error-message{position:relative}.verify-link i{font-weight:400;position:relative;top:-1px}.error-message i{position:absolute;top:2px;font-weight:400}.error-message .message{padding-left:15px;margin-left:0;white-space:initial;display:inline-block}.card-winner{background:#f8f9fa;height:80%;white-space:initial;padding:7px 12px}.card-winner p{white-space:initial}</style>");
  }


  /*
   *
   * Generate urls
   *
   */
  function generate_url ($cards) {
    $cards.each (function (i, card) {

      let $card = $(card).addClass ("urled")
        , url = $card.find (".card-image a").attr ("href")
        ;

      if (url.substr (0, 4) == "http") {
        display_error_message ($card, "", "fa fa-unlink", "External Url");
      }

      else {
        $card
          .data ("verify-url", `${url}verify/`)
          .data ("result-url", `${url}`)
          .find (".strong-700")
          .next ()
          .after (`<a href="${url}verify/" class="verify-link d-block pt-2 text-sm c-grey-light" target="_blank"><i class="fas fa-external-link"></i> Verify</a>`);
      }
    });
  }


  /*
   *
   * Display error message
   *
   */
  function display_error_message ($card, cname, icon, message) {

    cname = cname == "" ? "text-danger" : cname;
    icon = icon == "" ? "fas fa-times-circle" : icon;

    let error = `<span class="error-message d-block text-sm c-grey-light ${cname}"><i class="${icon}"></i><span class="message">${message}</span></span>`;

    $loading = $card
      .addClass ("url-illegal")
      .data ("result-url", null)
      .find (".loading");

    if ($loading.length > 0)
      $loading.replaceWith (error);

    else
      $card.find (".verify-link, .error-message").last ().after (error);
  }


  /*
   *
   * Retrieve premint result
   *
   */
  function queue_retrieve ($cards, idx, end) {

    // Loop end, remove all loading state
    if (idx > end) {
      $cards.find (".loading").remove ();
      return;
    }

    // Mark all cards as loading state
    if (idx == 0) {
      $cards
        .not (".url-illegal")
        .find (".card-body")
        .append (`<span class="loading"><i class="fas fa-circle-notch fa-spin"></i></span>`)
        .wrapInner ("<div class=\"card-info\" />");
    }

    let $card = $cards.eq (idx);

    // Illegal url, move to next
    if ($card.hasClass ("url-illegal")) {
      $card.addClass ("loaded");
      queue_retrieve ($cards, idx + 1, end);
      return;
    }

    retrieve_verify ($card, function () {
      setTimeout (function () {

        queue_retrieve ($cards, idx + 1, end);

      }, PREMINT.delay);
    });
  }


  /*
   *
   * Retrieve premint result
   *
   */
  function retrieve_verify ($card, next) {

    $.get ($card.data ("verify-url"))
      .done (function (html) {

        $embed = get_filtered_verify_html (html)
          .removeClass ("card-body").addClass ("card-verify text-center")
          .find (".mb-3").removeClass ("mb-3")
          .end ();

        $card.addClass ("loaded").find (".loading").remove ()
          .end ().find (".card-info").after ($("<div></div>").append ($embed));

      })
      .fail (function () {

        $card.addClass ("loaded").find (".loading").remove ()
          .end ().find (".card-info").after ($("<div></div>"));

      }).always (function () {

        retrieve_result ($card);
        next ();

      });
  }


  /*
   *
   * Retrieve premint result
   *
   */
  function retrieve_result ($card) {

    $.get ($card.data ("result-url"))
      .done (function (html) {

        if (html.indexOf ("This page is password protected") >= 0) {
          display_error_message ($card, "", "fas fa-lock", "This page is password protected");
          return;
        }

        else if (html.indexOf ("This project has been flagged and is no longer accepting entries") >= 0) {
          display_error_message ($card, "", "fas fa-flag", "This project has been flagged and is no longer accepting entries");
          return;
        }

        // Normal case
        if (html.indexOf ("user_is_winner") !== -1) {
          $embed = get_filtered_result_html (html, "#user_is_winner")
            .find (".card-body").addClass ("card-winner text-center").removeClass ("card-body");
        }

        else if (html.indexOf ("registration_status") !== -1) {
          $embed = get_filtered_result_html (html, "#registration_status")
            .find (".card-body").addClass ("card-result bg-success").removeClass ("card-body");
        }

        else {
          display_error_message ($card, "", "fas fa-times-circle", "This project has been flagged");
          return;
        }

        $embed.find ("a[href^=\"mailto:info@premint\"]").remove ();
        $embed.find ("a[href^=\"https://twitter.com/share\"]").remove ();

        $card.addClass ("loaded").find (".loading").remove ()
          .end ().find (".card-info").next ().append ($embed);

      })
      .fail (function () {

        display_error_message ($card, "", "fas fa-unlink", "Illegal Url");

      })
      .always (function () {

        if (typeof next !== "undefined")
          next ();
      });
  }


  /*
   *
   * Boot
   *
   */
  main ();

})(typeof jQuery == "undefined" ? false : jQuery);