<!DOCTYPE html>
<html>

<head>
    <title>Dispatcher API Test</title>
    <!-- <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet"> -->
    <link href="css/materialdesignicons.min.css" rel="stylesheet">
    <link href="css/vuetify.min.css" rel="stylesheet">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
</head>

<body>
    <div id="app">
        <v-app>
            <v-app-bar app>
                <v-toolbar-title>Dispatcher</v-toolbar-title>
                <v-spacer></v-spacer>
                <v-checkbox label="Expert Mode" v-model="EXPERTMODE"></v-checkbox>
            </v-app-bar>
            <v-content>
                <v-container> <!-- Device List-->
                    <v-data-table must-sort :footer-props="footerProps" 
                    :options="options" :loading="loadingD" loading-text="Loading... Please wait" 
                    :headers="devicesHeaders" item-key="_id" :items="deviceListData"
                    :single-expand="singleExpand" item-key="name" show-expand
                    class="elevation-1">
                        <template v-slot:top>
                            <v-toolbar flat>
                                <v-toolbar-title>Device List</v-toolbar-title>
                            </v-toolbar>
                        </template>
                        <template v-slot:no-data>
                            No Devices to show
                        </template>
                        <template v-slot:expanded-item="{ headers, item }">
                          <td :colspan="headers.length">
                            <section v-if="item.deviceType == 'birdyslim'">
<pre>Device ID: {{ item.deviceID }}</pre>
<pre v-if="!!item.poweredOn">Powered On: {{ item.poweredOn }}</pre>
<pre v-if="!!item.isCharging">Charging: {{ item.isCharging }}</pre>
<pre v-if="!!item.battery">Battery: {{ item.battery }}</pre>
<pre v-if="!!item.lastSeen">Last Seen: {{ item.lastSeen }}</pre>
<pre v-if="!!item.rssi">POCSAG RSSI: -{{ item.rssi }}dBm</pre>
<pre v-if="!!item.gps">GPS Position:
    Lat: {{ item.gps.latitude }}
    Lng: {{ item.gps.longitude }}
    Last Acquisition: {{ item.gps.lastGPSAcquisition }}m ago
</pre>
<pre v-if="!!item.lastLoRaPacket">
Last LoRaWAN Packet:
{{ item.lastLoRaPacket }}
</pre>
                            </section>
                          </td>
                        </template>
                    </v-data-table>
                </v-container>
                <hr>
                <v-container> <!-- Recent Messages -->
                    <v-data-table must-sort :footer-props="footerProps" 
                    :options="options" :loading="loadingM" loading-text="Loading... Please wait" 
                    :headers="recentMessagesHeaders" item-key="id" :items="recentMessageListData" :items-per-page="5"
                    :single-expand="singleExpandRM" item-key="name" show-expand
                    class="elevation-1">
                        <template v-slot:top>
                            <v-toolbar flat>
                                <v-toolbar-title>Message History</v-toolbar-title>
                                <v-spacer></v-spacer>

                                <v-dialog v-model="dialogNewMessage" fullscreen hide-overlay transition="dialog-bottom-transition">
                                    <template v-slot:activator="{ on, attrs }">
                                        <v-btn color="primary"  v-bind="attrs" v-on="on">
                                            <v-icon>mdi-email</v-icon>
                                            New Message
                                        </v-btn>
                                    </template>
                                    <v-card>
                                    <v-toolbar dark color="primary">
                                        <v-btn icon dark @click="dialogNewMessage = false">
                                        <v-icon>mdi-close</v-icon>
                                        </v-btn>
                                        <v-toolbar-title>New Message</v-toolbar-title>
                                        <v-spacer></v-spacer>
                                    </v-toolbar>
                                    <v-container v-if="EXPERTMODE">
                                        <b>Routing Parameters:</b>
                                        <v-row>
                                            <v-col cols="12" sm="12" md="6">
                                                <v-select :items="pagerTypes" v-model="newMSGData.pager.params.type" item-text="k" item-value="v" label="Delivery Type"></v-select>
                                            </v-col>
                                        </v-row>
                                        <v-row>
                                            <v-col cols="12" sm="12" md="6">
                                                <v-select :items="deviceType" v-model="newMSGData.pager.params.routing.device" item-text="k" item-value="v" label="Device"></v-select>
                                            </v-col>
                                        </v-row>
                                        <b>Delivery Targets:</b>
                                        <v-btn color="primary" @click="testMsg_addDeliveryTarget()">Add</v-btn>
                                        <v-row v-for="(connector, index) in newMSGData.pager.params.routing.connectors" :key="index">
                                            <v-col cols="6" sm="4" md="4">
                                                <v-select :items="connectorTypes" v-model="connector[0]" item-text="k" item-value="v" label="Gateway"></v-select>
                                            </v-col>
                                            <v-col cols="6" sm="4" md="4">
                                                <v-text-field v-model="connector[1]" label="Call ID"></v-text-field>
                                            </v-col>
                                            <v-col cols="6" sm="4" md="4">
                                                <v-btn color="error" @click="newMSGData.pager.params.routing.connectors.splice(index, 1)" icon><v-icon>mdi-delete</v-icon></v-btn>
                                            </v-col>
                                        </v-row>
                                        <v-row>
                                            <v-col cols="12" sm="12" md="6">
                                                <v-textarea v-model="newMSGData.pager.payload" label="Message"></v-select>
                                            </v-col>
                                        </v-row>
                                        <v-row>
                                            <v-col cols="12" sm="12" md="6">
                                            <v-btn color="success" dark text @click="testMsg_send()">Send</v-btn>
                                        </v-col>
                                        </v-row>
                                    </v-container>
                                    <v-container v-else>
                                        <v-row>
                                            <v-col cols="12" sm="12" md="6">
                                                <v-autocomplete
                                                    v-model="newMSGData.preset"
                                                    :items="presetSearchItems"
                                                    :loading="!presetSearchItems.length > 0"
                                                    color="white"
                                                    hide-no-data
                                                    dense
                                                    label="Profile"
                                                    placeholder="Start typing to Search"
                                                    prepend-icon="mdi-database-search"
                                                ></v-autocomplete>
                                            </v-col>
                                        </v-row>
                                        <v-row>
                                            <v-col cols="12" sm="12" md="6">
                                                <v-textarea v-model="newMSGData.pager.payload" label="Message"></v-select>
                                            </v-col>
                                        </v-row>
                                        <v-row>
                                            <v-col cols="12" sm="12" md="6">
                                            <v-btn color="success" dark text @click="testMsg_send()">Send</v-btn>
                                        </v-col>
                                        </v-row>
                                    </v-container>
                                    </v-card>
                                </v-dialog>
                            </v-toolbar>
                        </template>
                        <template v-slot:no-data>
                            No Messages to show
                        </template>
                        <template v-slot:expanded-item="{ headers, item }">
                          <td :colspan="headers.length">
                            <v-btn :disabled="item._routerData.recvAck" @click="apiACKMessage(item.id, 'recv')">manual RECV ACK</v-btn> 
                            <v-btn :disabled="item._routerData.readAck" @click="apiACKMessage(item.id, 'read')">manual READ ACK</v-btn> 
                                <pre>{{ item  }}</pre>
                          </td>
                        </template>
                    </v-data-table>
                </v-container>
            </v-content>
        </v-app>
    </div>

    <script src="js/vue/vue.js"></script>
    <script src="js/vue/vuetify.js"></script>
    <script src="js/vue/vue-resource_1.5.1.js"></script>
    <script>
        new Vue({
            el: '#app',
            vuetify: new Vuetify(),
            http: { root: '/' },
            data() {
                return {
                    EXPERTMODE:false,

                    dialogNewMessage: false,
                    presetSearchItems: [],
                    
                    loadingD: true,
                    loadingM: true,
                    search: '',
                    expanded: [],
                    singleExpand: true,
                    singleExpandRM: true,
                    options: {
                        itemsPerPage: -1,
                    },
                    footerProps: {
                        itemsPerPageOptions: [ -1, 5, 10, 20, 50, 75, 100 ]
                    },

                    deviceListData: [],
                    devicesHeaders: [
                        { text: 'ID', align: 'start', groupable: false, sortable: false, value: 'deviceID', },
                        { text: 'Type', value: 'deviceType', groupable: true },
                        { text: 'Last Seen', value: 'lastSeen', groupable: false },
                    ],

                    recentMessageListData: [],
                    recentMessagesHeaders: [
                        { text: 'ID', align: 'start', groupable: false, sortable: false, value: 'id', },
                        { text: 'Type', value: 'type', groupable: true, sortable: false },
                        { text: 'State', value: 'state', groupable: false, sortable: false },
                        { text: 'Date', value: 'date', groupable: false, sortable: false },
                        { text: 'Message', value: '_payload', groupable: false, sortable: false },
                    ],


                    pagerTypes: [
                        {k: 'Simple', v: 'simple'},
                        {k: 'Duplex', v: 'duplex'},
                    ],
                    deviceType: [
                        {k: 'Generic', v: 'generic'},
                        {k: 'Birdy Slim (IoT)', v: 'birdyslim'},
                    ],
                    connectorTypes: [
                        {k: 'Dummy', v: 'dummy'},
                        {k: 'POCSAG GW', v: 'pocsag'},
                        {k: 'DAPNET', v: 'dapnet'},

                        {k: 'e*Cityruf inetgw', v: 'ecityruf'},
                        {k: 'e*Cityruf Puppeteer', v: 'em-p-cityruf'},
                        {k: 'e*Cityruf alarmManager', v: 'em-a-cityruf'},

                        {k: 'e*2wayS Puppeteer', v: 'em-p-twoways'},
                        {k: 'e*2wayS alarmManager', v: 'em-a-twoways'},

                        {k: 'LoRaWAN TTNv3', v: 'lorawan'},
                    ],

                    newMSGData: {
                        "pager": {
                            "params": {
                                "type": "simple",
                                "routing": {
                                    "device": "generic",
                                    "connectors": [
                                        ["dummy","1234"]
                                    ]
                                }
                            },
                            "payload": "Test Message",
                        },
                        "preset": null,
                    }
                }
            },
            created() {
                this.refreshDevices()
                setInterval(this.refreshDevices, 1e3)

                this.refreshMessages()
                setInterval(this.refreshMessages, 1e3)

                this.$http.get(window.location.pathname + 'api/deliveryPresets')
                .then(response => {
                    console.log(response.body)
                    this.presetSearchItems = response.body.map(x => { return {
                        text: x.name,
                        value: x.key,
                        //Description
                    }})
                }, response => {
                })
            },
            methods: {
                refreshDevices() {
                    this.$http.get(window.location.pathname + 'api/devices').then(response => {
                        this.deviceListData = Object.keys(response.body).map(key => {
                            const item = response.body[ key ]
                            const keyData = key.split(':')
                            item.deviceType = keyData[ 0 ], item.deviceID = keyData[ 1 ]

                            item.lastSeen = new Date(item.lastSeen).toLocaleString('de')
                            //item.validStateText = this.validStateLUT[item.validState]
                            return item
                        })
                        //this.accountData.sort((a,b) => a.validState - b.validState)
                        this.loadingD = false
                    }, response => {
                    })
                },
                refreshMessages() {
                    this.$http.get(window.location.pathname + 'api/message/recent').then(response => {
                        this.recentMessageListData = response.body.map(msg => {
                            const stateArray = [msg._routerData.recvAck, msg._routerData.readAck, msg._routerData.response]
                            // msg.state = [ msg.type, stateArray.filter(x=>x!==false).length, ...stateArray ]
                            msg.state = '-'
                            if (msg.type === 'duplex') {
                                switch (stateArray.filter(x=>x!==false).length) {
                                    case 0: msg.state = '📨 Sent'; break;
                                    case 1: msg.state = '📬 Received'; break;
                                    case 2: msg.state = '👀 Read'; break;
                                    case 3: msg.state = '💬 Responded'; break;
                                }
                            }
                            if (msg._routerData.failed === true) msg.state = '❌ Failed'
                            msg.date = new Date(msg.date).toLocaleString('de')
                            return msg
                        })
                        this.loadingM = false
                    }, response => {
                    })
                },
                apiACKMessage(id, ackType) {
                    this.$http.get(
                        window.location.pathname + 'api/message/ack/'+[ackType, id].join('/')
                    ).then(x=>{})
                },
                testMsg_addDeliveryTarget() {
                    this.newMSGData.pager.params.routing.connectors.push(["dummy","1234"])
                },
                testMsg_send() {
                    if (this.EXPERTMODE) {
                        this.$http.post(window.location.pathname + 'api/message/advanced/', 
                        Object.assign({ ...this.newMSGData.pager.params }, { payload: this.newMSGData.pager.payload })
                        ).then(x=>{
                            this.dialogNewMessage = false
                        })
                    } else {
                        console.log(this.newMSGData.preset)
                        this.$http.post(window.location.pathname + 'api/message/preset/', 
                        Object.assign({ preset: this.newMSGData.preset }, { payload: this.newMSGData.pager.payload })
                        ).then(x=>{
                            this.dialogNewMessage = false
                        })
                    }
                }
            }

        })
    </script>
</body>

</html>