<template>
    <div class="container-xxl" role="main">
        <div class="page-header">
            <h1>Inverter Settings</h1>
        </div>

        <BootstrapAlert v-model="showAlert" dismissible :variant="alertType">
            {{ alertMessage }}
        </BootstrapAlert>

        <div class="card">
            <div class="card-header text-white bg-primary">Add a new Inverter</div>
            <div class="card-body">
                <form class="form-inline" v-on:submit.prevent="onSubmit">
                    <div class="form-group">
                        <label>Serial</label>
                        <input v-model="inverterData.serial" type="number" class="form-control ml-sm-2 mr-sm-4 my-2"
                            required />
                    </div>
                    <div class="form-group">
                        <label>Name</label>
                        <input v-model="inverterData.name" type="text" class="form-control ml-sm-2 mr-sm-4 my-2"
                            maxlength="31" required />
                    </div>
                    <div class="ml-auto text-right">
                        <button type="submit" class="btn btn-primary my-2">Add</button>
                    </div>
                </form>
            </div>
        </div>

        <div class="card mt-5">
            <div class="card-header text-white bg-primary">Inverter List</div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table">
                        <thead>
                            <tr>
                                <th scope="col">Serial</th>
                                <th>Name</th>
                                <th>Type</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="inverter in sortedInverters" v-bind:key="inverter.id">

                                <td>
                                    {{ inverter.serial }}
                                </td>
                                <td>
                                    {{ inverter.name }}
                                </td>
                                <td>
                                    {{ inverter.type }}
                                </td>
                                <td>
                                    <a href="#" class="icon">
                                        <BIconTrash v-on:click="onDelete(inverter.id)" />
                                    </a>
                                    <a href="#" class="icon">
                                        <BIconPencil v-on:click="onEdit(inverter)" />
                                    </a>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="modal" id="inverterEdit" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Edit Inverter</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">

                        <form>
                            <div class="mb-3">
                                <label for="inverter-serial" class="col-form-label">Serial:</label>
                                <input v-model="editInverterData.serial" type="number" id="inverter-serial"
                                    class="form-control" />
                            </div>
                            <div class="mb-3">
                                <label for="inverter-name" class="col-form-label">Name:</label>
                                <input v-model="editInverterData.name" type="text" id="inverter-name"
                                    class="form-control" maxlength="31" />
                            </div>

                            <div class="mb-3" v-for="(max, index) in editInverterData.max_power" :key="`${index}`">
                                <label :for="`inverter-max_${index}`" class="col-form-label">Max power string {{ index +
                                        1
                                }}:</label>
                                <div class="input-group">
                                    <input type="number" class="form-control" :id="`inverter-max_${index}`" min="0"
                                        v-model="editInverterData.max_power[index]"
                                        :aria-describedby="`inverter-maxDescription_${index}`" />
                                    <span class="input-group-text" :id="`inverter-maxDescription_${index}`">W</span>
                                </div>
                            </div>
                        </form>

                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" @click="onCancel"
                            data-bs-dismiss="modal">Cancel</button>
                        <button type="button" class="btn btn-primary" @click="onEditSubmit(editId)">Save
                            changes</button>
                    </div>
                </div>
            </div>
        </div>

    </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import * as bootstrap from 'bootstrap';
import BootstrapAlert from "@/components/partials/BootstrapAlert.vue";

declare interface Inverter {
    id: string,
    serial: number,
    name: string,
    type: string
    max_power: number[]
}

export default defineComponent({
    components: {
        BootstrapAlert,
    },
    data() {
        return {
            modal: {} as bootstrap.Modal,
            editId: "-1",
            inverterData: {} as Inverter,
            editInverterData: {} as Inverter,
            inverters: [] as Inverter[],
            alertMessage: "",
            alertType: "info",
            showAlert: false,
        };
    },
    mounted() {
        this.modal = new bootstrap.Modal('#inverterEdit');
    },
    created() {
        this.getInverters();
    },
    computed: {
        sortedInverters() {
            return this.inverters.slice().sort((a, b) => {
                return a.serial - b.serial;
            });
        },
    },
    methods: {
        getInverters() {
            fetch("/api/inverter/list")
                .then((response) => response.json())
                .then((data) => (this.inverters = data.inverter));
        },
        onSubmit() {
            const formData = new FormData();
            formData.append("data", JSON.stringify(this.inverterData));

            fetch("/api/inverter/add", {
                method: "POST",
                body: formData,
            })
                .then(function (response) {
                    if (response.status != 200) {
                        throw response.status;
                    } else {
                        return response.json();
                    }
                })
                .then(
                    (response) => {
                        this.alertMessage = response.message;
                        this.alertType = response.type;
                        this.showAlert = true;
                    }
                )
                .then(() => { this.getInverters() });

            this.inverterData.serial = 0;
            this.inverterData.name = "";
        },
        onDelete(id: string) {
            const formData = new FormData();
            formData.append("data", JSON.stringify({ id: id }));

            fetch("/api/inverter/del", {
                method: "POST",
                body: formData,
            })
                .then(function (response) {
                    if (response.status != 200) {
                        throw response.status;
                    } else {
                        return response.json();
                    }
                })
                .then(
                    (response) => {
                        this.alertMessage = response.message;
                        this.alertType = response.type;
                        this.showAlert = true;
                    }
                )
                .then(() => { this.getInverters() });
        },
        onEdit(inverter: Inverter) {
            this.modal.show();
            this.editId = inverter.id;
            this.editInverterData.serial = inverter.serial;
            this.editInverterData.name = inverter.name;
            this.editInverterData.type = inverter.type;
            this.editInverterData.max_power = inverter.max_power;
        },
        onCancel() {
            this.editId = "-1";
            this.editInverterData.serial = 0;
            this.editInverterData.name = "";
            this.editInverterData.max_power = [];
            this.modal.hide();
        },
        onEditSubmit(id: string) {
            const formData = new FormData();
            this.editInverterData.id = id;
            formData.append("data", JSON.stringify(this.editInverterData));

            fetch("/api/inverter/edit", {
                method: "POST",
                body: formData,
            })
                .then(function (response) {
                    if (response.status != 200) {
                        throw response.status;
                    } else {
                        return response.json();
                    }
                })
                .then(
                    (response) => {
                        this.alertMessage = response.message;
                        this.alertType = response.type;
                        this.showAlert = true;
                    }
                )
                .then(() => { this.getInverters() });

            this.editId = "-1";
            this.editInverterData.serial = 0;
            this.editInverterData.name = "";
            this.editInverterData.type = "";
            this.editInverterData.max_power = [];
            this.modal.hide();
        },
    },
});
</script>