doctype html
html(lang='en')
    head
        meta(charset="utf-8")
        meta(name="viewport" content="width=device-width, initial-scale=1")
        link(rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.4/css/bulma.min.css")
        title ELEC0017 Project
        script(src="https://cdn.jsdelivr.net/npm/vue")
        script(src="https://unpkg.com/axios/dist/axios.min.js")
    body
        #app
            .tabs
                ul
                    li(v-for="menu in menus" :class="{'is-active': menu_selected === menu}")
                        a(@click="menu_selected = menu") {{ menu }}

            section.section
                article.message.is-warning(v-show="error")
                    .message-header
                        p Error
                        button.delete(@click="error = null")
                    .message-body {{ error }}
                template(v-if="menu_selected === 'admins'")
                    include admins
                template(v-else-if="menu_selected === 'boards'")
                    include boards
                template(v-else-if="menu_selected === 'logs'")
                    include logs
                template(v-else)
                    include index

        script.
          axios.defaults.validateStatus = function (status) {
            return status >= 200 && status < 410;
          }
          axios.interceptors.response.use(function (response) {
            if (response.status >= 400) {
              app.error = response.data;
              return Promise.reject(response);
            } else if (response.status == 307 || response.status == 306) {
              // console.log(response);
            }
            return response;
          }, function (error) {
            return Promise.reject(error);
          });

          var app = new Vue({
            el: '#app',
            data: {
              menus: ['index', 'boards', 'admins', 'logs'],
              menu_selected: 'index',
              config: {},
              admin: {new_user: "", new_pass: ""},
              board: {new_id: "", new_key: "", new_keysize: 128},
              error: "",
              srvlogs: [],
              log_timer: null
            },
            methods: {
              get_logs: function() {
                  let self = this;
                  axios.get('/admin/logs').then(function (res) {
                      self.srvlogs = res.data;
                      self.log_timer = window.setTimeout(self.get_logs, 1500);
                  })
              },
              admin_delete: function(admin) {
                let self = this;
                axios.delete('/admin/user/' + admin).then(function (res) {
                  self.config = res.data;
                })
              },
              admin_create: function () {
                let self = this;
                const params = new URLSearchParams();
                params.append('username', self.admin.new_user);
                params.append('password', self.admin.new_pass);
                axios.post('/admin/user', params).then(function (res) {
                  self.admin.new_user = ""
                  self.admin.new_pass = ""
                  self.config = res.data;
                })
              },
              board_delete: function (id) {
                let self = this;
                axios.delete('/admin/board/' + id).then(function (res) {
                  self.config = res.data;
                })
              },
              board_create: function () {
                let self = this;
                const params = new URLSearchParams();
                params.append('id', self.board.new_id);
                params.append('key', self.board.new_key);
                params.append('keysize', self.board.new_keysize);
                axios.post('/admin/board', params).then(function (res) {
                    self.board = {new_id: "", new_key: "", new_keysize: 128}
                    self.config = res.data;
                })
              }
            },
            mounted: function () {
              let self = this;
              axios.get('/admin/config').then(function (res) {
                self.config = res.data;
              })
            },
            watch: {
              menu_selected: function (now, old) {
                let self = this;
                if (now === old) return;
                if (now==="logs") {
                    console.log("Timer ready");
                    self.get_logs();
                } else {
                    console.log("Timer removed");
                    window.clearTimeout(self.log_timer);
                }
              }
            },
            filters: {
              timeSince: function (datestr) {
                if (datestr === "0001-01-01T00:00:00Z" || datestr === "1970-01-01T01:00:00+01:00") return "never";
                let date = new Date(datestr);
                let delta = new Date() - date;
                if (delta > 1000*60*60*24) {
                  let year = date.getFullYear();
                  let month = '' + (date.getMonth() + 1);
                  let day = '' + date.getDate();
                  if (month.length < 2) month = '0' + month;
                  if (day.length < 2) day = '0' + day;
                  return [year, month, day].join('/');
                }
                let seconds = Math.floor(delta / 1000);
                let interval = Math.floor(seconds / 3600);
                if (interval > 1) {
                  return interval + " hours";
                }
                interval = Math.floor(seconds / 60);
                if (interval > 1) {
                  return interval + " minutes";
                }
                return Math.floor(seconds) + " seconds";
              }
            }
          })
