<!DOCTYPE html>
<html>

<head>
  <title>Stock Ditalization & Simulation Trading Platform</title>

  <!-- Viewport mobile tag for sensible mobile support -->
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />

  <% /* If you want to discourage search engines from indexing this site, uncomment the following line: */%>
    <% /* <meta name="robots" content="noindex" />
    */%>

    <!--
        Stylesheets and Preprocessors
        ==============================
        You can always bring in CSS files manually with `<link>` tags, or asynchronously
        using a solution like AMD (RequireJS).  Or, if you like, you can take advantage
        of Sails' conventional asset pipeline (boilerplate Gruntfile).
        By default, stylesheets from your `assets/styles` folder are included
        here automatically (between STYLES and STYLES END). Both CSS (.css) and LESS (.less)
        are supported. In production, your styles will be minified and concatenated into
        a single file.
        To customize any part of the built-in behavior, just edit `tasks/pipeline.js`.
        For example, here are a few things you could do:
            + Change the order of your CSS files
            + Import stylesheets from other directories
            + Use a different or additional preprocessor, like SASS, SCSS or Stylus
    -->

    <!--STYLES-->
    <link rel="stylesheet" href="/styles/importer.css">
    <!--STYLES END-->

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.0/css/bulma.min.css" />
    <style>
      #stockByMic {
        max-height: 30vh;
        overflow: auto;
      }

      #priceStock {
        float: right;
      }
    </style>
</head>

<script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script>
<script crossorigin src="https://unpkg.com/@daily-co/daily-js"></script>
<script src="https://cdn.jsdelivr.net/npm/luxon@1.24.1"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.0.0-beta.9/dist/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-luxon@0.2.1"></script>
<script src="https://www.chartjs.org/chartjs-chart-financial/chartjs-chart-financial.js"
  type="text/javascript"></script>
<script src="https://cdn.jsdelivr.net/npm/echarts@5.0.2/dist/echarts.min.js"></script>
<link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.1/css/bulma.min.css"
    />
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"
    />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<body>
  <nav class="navbar is-black" role="navigation" aria-label="main navigation">
    <div class="container">
      <div class="navbar-brand">
        <a class="navbar-item" href="/">
          <img src="https://th.bing.com/th/id/OIP.qpjeNYihWYtgYTEdknvTHAHaHa?pid=ImgDet&rs=1" width="75" height="28" />
        </a>

        <a role="button" class="navbar-burger" aria-label="menu" aria-expanded="false" data-target="ex">
          <span aria-hidden="true"></span>
          <span aria-hidden="true"></span>
          <span aria-hidden="true"></span>
        </a>
      </div>

      <div id="ex" class="navbar-menu">
        <!-- hidden on mobile -->
        <div class="navbar-start">
          <!-- navbar items -->
          <a class="navbar-item" href="/"> Market News </a>
          <a class="navbar-item" href="/stock/search"> Stock Search </a>
          <% if (req.session.role=='member' ) { %>
            <a class="navbar-item" href="/user/clients_2"> My Trading </a>
            <% } %>
              <!--<% if (req.session.role=='admin' ) { %>
            <a class="navbar-item" href="/"> Admin </a>
            <% } %>-->
        </div>

        <div class="navbar-end">
          <!-- navbar items -->
          <div class="navbar-item">
            <div class="buttons">
              <% if (!req.session.username) { %>
                <!--no username in session, recover login and signup button-->
                <button class="button is-primary modal-button" data-target="modal-signup" aria-haspopup="true"
                  onclick="activateSignup()">
                  <strong>Sign up</strong>
                </button>
                <button class="button is-light modal-button" data-target="modal-login" aria-haspopup="true"
                  onclick="activateLogin()">
                  Log in
                </button>
                <% } else {%>
                  <!-- have username -->
                  <a class="button is-black" href="">
                    <strong>hi, <%= req.session.username%> (role: <%= req.session.role%>)
                    </strong>
                  </a>
                  <a class="button is-black" href="#">
                    <strong>Your Balance: <p id="balance_id"></p></strong>
                  </a>
                  <a class="button is-black" href="#">
                    <strong> Trading Status: <p id="trade_status"></p></strong>
                  </a>
                  <a class="button is-light" href="/user/logout"> Log out </a>
                  <% } %>
            </div>
          </div>
        </div>
      </div>
    </div>
  </nav>

  <!-- login page -->
  <div id="modal-login" class="modal">
    <div class="modal-background"></div>
    <div class="modal-card">
      <header class="modal-card-head">
        <p class="modal-card-title">Login</p>
        <button class="delete" aria-label="close" onclick="deactivateLogin();"></button>
      </header>
      <form action="/user/login" method="POST" onsubmit="submitForm(this); return false">
        <section class="modal-card-body">
          <!-- Content ... -->
          <div class="field">
            <p class="control has-icons-left has-icons-right">
              <input class="input" type="text" placeholder="Username" name="username" />
              <span class="icon is-small is-left">
                <i class="fas fa-user"></i>
              </span>
            </p>
          </div>
          <div class="field">
            <p class="control has-icons-left">
              <input class="input" type="password" placeholder="Password" name="password" />
              <span class="icon is-small is-left">
                <i class="fas fa-lock"></i>
              </span>
            </p>
          </div>
        </section>
        <footer class="modal-card-foot">
          <button class="button is-success" type="submit">Login</button>
        </footer>
      </form>
    </div>
  </div>


  <!-- Signup page -->
  <div id="modal-signup" class="modal">
    <div class="modal-background"></div>
    <div class="modal-card">
      <header class="modal-card-head">
        <p class="modal-card-title">Signup</p>
        <button class="delete" aria-label="close" onclick="deactivateSignup();"></button>
      </header>
      <form action="/user/signup" method="POST" onsubmit="submitSignup(this); return false">
        <section class="modal-card-body">
          <!-- Content ... -->
          <div class="field">
            <p class="control has-icons-left has-icons-right">
              <input class="input" type="text" placeholder="Username" name="username" required />
              <span class="icon is-small is-left">
                <i class="fas fa-user"></i>
              </span>
            </p>
          </div>
          <div class="field">
            <p class="control has-icons-left">
              <input class="input" type="password" placeholder="Password" name="password" required />
              <span class="icon is-small is-left">
                <i class="fas fa-lock"></i>
              </span>
            </p>
          </div>
          <div class="field">
            <p class="control">
              <label class="label">Role: </label>
            <div class="control is-expanded">
              <div class="select">
                <select name="role">
                  <option>member</option>
                  <option>nonmember</option>
                </select>
              </div>
            </div>
            </p>
          </div>
        </section>
        <footer class="modal-card-foot">
          <button class="button is-success" type="submit">Signup</button>
        </footer>
      </form>
    </div>
  </div>

  <%- body %>


    <!--
        Client-side Templates
        ========================

        HTML templates are important prerequisites of modern, rich client applications.
        To work their magic, frameworks like React, Vue.js, Angular, Ember, and Backbone
        require that you load these templates client-side.

        By default, your Gruntfile is configured to automatically load and precompile
        client-side JST templates in your `assets/templates` folder, then
        include them here automatically (between TEMPLATES and TEMPLATES END).

        To customize this behavior to fit your needs, just edit `tasks/pipeline.js`.
        For example, here are a few things you could do:

            + Import templates from other directories
            + Use a different view engine (handlebars, dust, pug/jade, etc.)
            + Internationalize your client-side templates using a server-side
              stringfile before they're served.
    -->

    <!--TEMPLATES-->
    <!--TEMPLATES END-->

    <!--
        Server-side View Locals
        ========================

        Sometimes, it's convenient to get access to your server-side view locals from
        client-side JavaScript.  This can improve page load times, remove the need for
        extra AJAX requests, and make your client-side code easier to understand and
        to maintain.  Sails provides a simple mechanism for accessing dynamic view
        locals: the "exposeLocalsToBrowser()" view partial.

        For more information on using this built-in feature, see:
        https://sailsjs.com/docs/concepts/views/locals#?escaping-untrusted-data-using-exposelocalstobrowser

    -->

    <!--

      Client-side Javascript
      ========================

      You can always bring in JS files manually with `script` tags, or asynchronously
      on the client using a solution like AMD (RequireJS).  Or, if you like, you can
      take advantage of Sails' conventional asset pipeline (boilerplate Gruntfile).

      By default, files in your `assets/js` folder are included here
      automatically (between SCRIPTS and SCRIPTS END).  Both JavaScript (.js) and
      CoffeeScript (.coffee) are supported. In production, your scripts will be minified
      and concatenated into a single file.

      To customize any part of the built-in behavior, just edit `tasks/pipeline.js`.
      For example, here are a few things you could do:

          + Change the order of your scripts
          + Import scripts from other directories
          + Use a different preprocessor, like TypeScript

    -->

    <!--SCRIPTS-->
    <script src="/dependencies/sails.io.js"></script>
    <!--SCRIPTS END-->
</body>

<script>
  //activate window to show the details of recommendation index
  function activateLogin() {
    document.getElementById("modal-login").className = "modal is-active";
  }

  //cancel the window
  function deactivateLogin() {
    document.getElementById("modal-login").className = "modal";
  }

  //打开注册页面
  function activateSignup() {
    document.getElementById("modal-signup").className = "modal is-active";
  }

  //关闭注册页面
  function deactivateSignup() {
    document.getElementById("modal-signup").className = "modal";
  }

  //login form validation
  async function submitForm(formElem) {
    var response = await fetch(formElem.action, {
      method: formElem.method,
      body: new FormData(formElem),
    });

    if (response.ok) {
      var user = await response.json();
      alert("Welcome, " + user.username);
      location.assign("/");
    } else if (response.status == 401) {
      var msg = await response.json();
      alert(msg);
    } else {
      alert(response.statusText);
    }
  }

  async function getUserInformation() {
    var response = await fetch("/user/list", {
      method: "POST",
    })

    if (response.ok) {
      var user = await response.json();

      var obj_balance = document.getElementById("balance_id");
      var obj_status = document.getElementById("trade_status");
      obj_balance.innerHTML = user.balances;

      if (user.tradeStatus == 1) {
        obj_status.innerHTML = "Normal";
      } else {
        obj_status.innerHTML = "Locked";
      }

    } else {
      alert(response.statusText);
    }
  }



  setInterval(function () {
    console.log('<%= req.session.username%>');
    if ('<%= req.session.username%>') {
      getUserInformation();
    }
  }, 5000);

  //sign up
  async function submitSignup(formElem) {

    var data_form = new FormData(formElem);

    if (data_form.get("role") == "member") {
      data_form.append("balances", 500000);
      data_form.append("assets", 500000);
      data_form.append("tradeStatus", 1);
      data_form.append("tradeCount", 4);
    } else {
      data_form.append("balances", 0);
      data_form.append("assets", 0);
      data_form.append("tradeStatus", 0);
      data_form.append("tradeCount", 0);
    }

    var response = await fetch(formElem.action, {
      method: formElem.method,
      body: data_form,
    });

    if (response.ok) {

      var user = await response.json();

      alert(user.username + " signed up successfully. ");

      location.assign("/");

    } else if (response.status == 409) {
      alert("User exist");
    } else {
      alert(response.statusText);
    }
  }

  document.addEventListener("DOMContentLoaded", () => {
    // Get all "navbar-burger" elements
    const $navbarBurgers = Array.prototype.slice.call(
      document.querySelectorAll(".navbar-burger"),
      0
    );

    // Check if there are any navbar burgers
    if ($navbarBurgers.length > 0) {
      // Add a click event on each of them
      $navbarBurgers.forEach((el) => {
        el.addEventListener("click", () => {
          // Get the target from the "data-target" attribute
          const target = el.dataset.target;
          const $target = document.getElementById(target);

          // Toggle the "is-active" class on both the "navbar-burger" and the "navbar-menu"
          el.classList.toggle("is-active");
          $target.classList.toggle("is-active");
        });
      });
    }
  });
</script>

</html>