<template>
  <md-dialog :md-active.sync="show" @close="show=false">
    <div class="md-layout md-alignment-bottom-center">
      <div class="md-layout-item md-size-100 md-small-size-100 md-alignment-bottom-center rounded-only">
        <h1 v-if="loading" style="text-align: center">Загрузка</h1>
        <div v-else>
          <LineChartGenerator :data="chartData" :dataset-id-key="'label'" :chart-id="'line-chart'" :height="400" :width="request.indexOf('days')>=0?600:1200"></LineChartGenerator>
          <div style="padding-right: 2.5%; padding-left: 2.5%;">
            <md-field style="margin: 0% 0%;">
              <label style="font-family: tf2secondary">Выбрать период</label>
              <md-select @md-selected="onLoad"  v-model="request" :mdClass="'ssm'" >
                <md-option :value="'api/stats/graph/peak/of/days'">По дням</md-option>
                <md-option :value="'api/stats/graph/peak/of/minutes'">По минутам</md-option>
              </md-select>
            </md-field>
            <md-field v-if="request === 'api/stats/graph/peak/of/minutes'" style="margin: 0% 0%;">
              <label style="font-family: tf2secondary">Минутная переодичность</label>
              <md-select @md-selected="onLoad"  v-model="request_minutes" :mdClass="'ssm'" >
                <md-option v-for="minutes in [1,5,10,15,30]" :key="minutes" :value="`&minutes=${minutes}`">Каждые {{minutes}} минут</md-option>
              </md-select>
            </md-field>
            <md-field style="margin: 0% 0%;">
              <label style="font-family: tf2secondary">Выбрать сервер</label>
              <md-select @md-selected="onLoad"  v-model="srv" :mdClass="'ssm'" >
                <md-option :value="''">Выбрать все</md-option>
                <md-option  v-for="srv in $API.getServers4Selector()" :key="srv['srv']" :value="srv['srv']">{{srv['name']}}</md-option>
              </md-select>
            </md-field>
            <md-field style="margin: 0% 0%;">
              <label style="font-family: tf2secondary">Выбрать количество дней</label>
              <md-select @md-selected="onLoad"  v-model="limit" :mdClass="'ssm'" >
                <md-option v-for="days in [1, 7, 14, 21, 28]" :key="days" :value="days">{{days}} дней</md-option>
              </md-select>
            </md-field>
            <md-button style="float: right" class="btn-default" v-on:click="showMe(false)">Закрыть</md-button>
          </div>
        </div>
      </div>
    </div>
  </md-dialog>
</template>

<script>
import { Line as LineChartGenerator } from 'vue-chartjs'
import axios from "axios";
import Random from "@/api/Random";

export default {
  name: "PlayersGraph",
  data: () => ({
    show: false,
    loading: false,
    chartData: {"labels":[], "datasets":[]},
    srv: "",
    limit: 7,
    request: "api/stats/graph/peak/of/days",
    request_minutes: "&minutes=5"
  }),
  components: { LineChartGenerator },
  methods: {
    showMe(action) {
      this.srv = ""
      this.show = action === undefined ? !this.show : action;
      if (action === true) {
        this.$API.create_server_websocket();
        this.onLoad();
      }
    },
    onLoad() {
      this.loading = true;
      axios.get(`${this.request}?limit=${this.limit}&server_id=${this.srv}` + this.request_minutes + Random.getRndWebAppend()).then(
          response => {
            //console.log(response.data);
            const data = response.data.length > 0 && 'date' in response.data[0]?response.data.reverse():response.data;
            this.chartData = {"labels":[], "datasets":[]};
            for (const i in data) {
              this.chartData.labels.push("date" in data[i]?data[i].date:data[i].timestamp);
            }
            if (data.length > 0 && 'max' in data[0])
              this.chartData.datasets.push({"label":"Пик игроков", backgroundColor: '#ff0000', data: data.map(d => d['max'])})

            if (data.length > 0 && 'avg' in data[0])
              this.chartData.datasets.push({"label":"Среднее количество игроков", backgroundColor: '#fff900', data: data.map(d => d['avg'])})
            //console.log(this.chartData);
          }
      ).catch().finally(() => this.loading = false)
    }
  }
}
</script>