<template>
    <section v-if="!addBool"
        :class="['solution-checklist-information', darkMode ? 'section-darkmode' : 'section-lightmode']">
        <div :class="['label', darkMode ? 'label-darkmode' : 'label-lightmode']">Checklist:</div>
        <table class="data-table" id="solution-checkklist">
            <tbody>
                <tr :class="['table-row', darkMode ? 'tr-head-darkmode' : 'tr-head-lightmode']" id="table-head">
                    <th
                        :class="['Step', darkMode ? 'th-darkmode' : 'th-lightmode', darkMode ? 'Step-darkmode' : 'Step-lightmode']">
                        Step</th>
                    <th
                        :class="['Asset', darkMode ? 'th-darkmode' : 'th-lightmode', darkMode ? 'Asset-darkmode' : 'Asset-lightmode']">
                        Asset</th>
                    <th
                        :class="['Task', darkMode ? 'th-darkmode' : 'th-lightmode', darkMode ? 'Task-darkmode' : 'Task-lightmode']">
                        Task</th>
                    <th :class="['Comments', darkMode ? 'th-darkmode' : 'th-lightmode']">Comments</th>
                </tr>
                <tr v-for="todo in solTodos" :key="todo.primaryID"
                    :class="['table-row', darkMode ? 'tr-darkmode' : 'tr-lightmode']" id="row-1">
                    <td
                        :class="['Step', darkMode ? 'td-darkmode' : 'td-lightmode', darkMode ? 'Step-darkmode' : 'Step-lightmode']">
                        {{ todo.step }}</td>
                    <td v-if="!editable"
                        :class="['Asset', darkMode ? 'td-darkmode' : 'td-lightmode', darkMode ? 'Asset-darkmode' : 'Asset-lightmode']">
                        {{ todo.asset }}</td>
                    <td v-if="editable"
                        :class="['Asset', darkMode ? 'td-darkmode' : 'td-lightmode', darkMode ? 'Asset-darkmode' : 'Asset-lightmode']">
                        <select id="customersDropDownChosenCI" v-model="todo.asset" @change="updateSolTodo(todo)"
                            :class="[darkMode ? 'select-darkmode' : 'select-lightmode']">
                            <option v-for="ci in configItemList" :key="ci.primaryID">
                                {{ ci.assetName }}
                            </option>
                        </select>
                    </td>
                    <td v-if="!editable"
                        :class="['Task', darkMode ? 'td-darkmode' : 'td-lightmode', darkMode ? 'Task-darkmode' : 'Task-lightmode']">
                        {{ todo.task }}</td>
                    <td v-if="editable"
                        :class="['Task', darkMode ? 'td-darkmode' : 'td-lightmode', darkMode ? 'Task-darkmode' : 'Task-lightmode']">
                        <input type="text" v-model="todo.task" @change="updateSolTodo(todo)"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                    </td>
                    <td v-if="!editable" :class="['Comments', darkMode ? 'td-darkmode' : 'td-lightmode']">{{
        todo.comments }}</td>
                    <td v-if="editable" :class="['Comments', darkMode ? 'td-darkmode' : 'td-lightmode']">
                        <input type="text" v-model="todo.comments" @change="updateSolTodo(todo)"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                        <button :class="[darkMode ? 'deleteSolTodos-darkmode' : 'deleteSolTodos-lightmode']"
                            @click="deleteSolTodo(todo.primaryID)">-</button>
                    </td>
                </tr>
            </tbody>
            <tr v-if="editable && addRow" :class="['table-row', darkMode ? 'tr-darkmode' : 'tr-lightmode']" id="row-1">
                <td
                    :class="['Step', darkMode ? 'td-darkmode' : 'td-lightmode', darkMode ? 'Step-darkmode' : 'Step-lightmode']">
                    {{ newStepTodo }}
                </td>
                <td
                    :class="['Asset', darkMode ? 'td-darkmode' : 'td-lightmode', darkMode ? 'Asset-darkmode' : 'Asset-lightmode']">
                    <select id="customersDropDownChosenCI" v-model="newAssetTodo"
                        :class="[darkMode ? 'select-darkmode' : 'select-lightmode']">
                        <option v-for="ci in configItemList" :key="ci.primaryID">
                            {{ ci.assetName }}
                        </option>
                    </select>
                </td>
                <td
                    :class="['Task', darkMode ? 'td-darkmode' : 'td-lightmode', darkMode ? 'Task-darkmode' : 'Task-lightmode']">
                    <input type="text" v-model="newTaskTodo"
                        :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                </td>
                <td :class="['Comments', darkMode ? 'td-darkmode' : 'td-lightmode']"><input type="text"
                        v-model="newCommentsTodo"
                        :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']"> <button
                        :class="[darkMode ? 'saveSolTodos-darkmode' : 'saveSolTodos-lightmode']"
                        @click="addSolTodo()">Save</button> <button
                        :class="[darkMode ? 'deleteLastSolTodos-darkmode' : 'deleteLastSolTodos-lightmode']"
                        @click="deleteNewRow()">-</button>
                </td>
            </tr>
        </table>
    </section>
    <section v-if="editable && !addBool" id="editSolTodos">
        <button :class="[darkMode ? 'editSolTodos-darkmode' : 'editSolTodos-lightmode']"
            @click="addChecklistRow()">+</button>
    </section>
    <section v-if="addBool"
        :class="['solution-checklist-information', darkMode ? 'section-darkmode' : 'section-lightmode']">
        <div :class="['label', darkMode ? 'label-darkmode' : 'label-lightmode']">Checklist:</div>
        <table class="data-table" id="template-checklist">
            <tbody>
                <tr :class="['table-row', darkMode ? 'tr-head-darkmode' : 'tr-head-lightmode']" id="table-head">
                    <th
                        :class="['Step', darkMode ? 'th-darkmode' : 'th-lightmode', darkMode ? 'Step-darkmode' : 'Step-lightmode']">
                        Step</th>
                    <th
                        :class="['Asset', darkMode ? 'th-darkmode' : 'th-lightmode', darkMode ? 'Asset-darkmode' : 'Asset-lightmode']">
                        Asset</th>
                    <th
                        :class="['Task', darkMode ? 'th-darkmode' : 'th-lightmode', darkMode ? 'Task-darkmode' : 'Task-lightmode']">
                        Task</th>
                    <th :class="['Comments', darkMode ? 'th-darkmode' : 'th-lightmode']">Comments</th>
                </tr>
                <tr v-for="(newT, index) in newTodos" :key="index"
                    :class="['table-row', darkMode ? 'tr-darkmode' : 'tr-lightmode']" id="row-1">
                    <td
                        :class="['Step', darkMode ? 'td-darkmode' : 'td-lightmode', darkMode ? 'Step-darkmode' : 'Step-lightmode']">
                        {{ newT.step }}
                    </td>
                    <td
                        :class="['Asset', darkMode ? 'td-darkmode' : 'td-lightmode', darkMode ? 'Asset-darkmode' : 'Asset-lightmode']">
                        <select id="customersDropDownChosenCI" v-model="newT.asset"
                            :class="[darkMode ? 'select-darkmode' : 'select-lightmode']">
                            <option v-for="ci in configItemList" :key="ci.primaryID">
                                {{ ci.assetName }}
                            </option>
                        </select>
                    </td>
                    <td
                        :class="['Task', darkMode ? 'td-darkmode' : 'td-lightmode', darkMode ? 'Task-darkmode' : 'Task-lightmode']">
                        <input type="text" v-model="newT.task"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
                    </td>
                    <td :class="['Comments', darkMode ? 'td-darkmode' : 'td-lightmode']"> <input type="text"
                            v-model="newT.comments"
                            :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']"> <button
                            :class="[darkMode ? 'deleteSolTodos-darkmode' : 'deleteLastSolTodos-lightmode']"
                            @click="deleteSolTodoFromNewTodos(index)">-</button>
                    </td>
                </tr>
            </tbody>
        </table>
    </section>
    <section v-if="addBool" id="editSolTodos">
        <button :class="[darkMode ? 'editSolTodos-darkmode' : 'editSolTodos-lightmode']"
            @click="addRowForNewSol()">+</button>
    </section>
    <section v-if="addBool" id="saveNewSol">
        <button :class="[darkMode ? 'saveNewSol-darkmode' : 'saveNewSol-lightmode']" @click="addSol()">Save</button>
    </section>
</template>


<script setup>
import { ref, onMounted, watch } from 'vue';
import Axios from '../axios.config.js';
import clientsideConfig from '../../clientsideConfig.js';
import { useStore } from 'vuex';
import { computed } from 'vue';

const store = useStore();
const modeChanged = computed(() => store.state.updateDarkMode);

const addBool = computed(() => store.state.new);
const editable = computed(() => store.state.editable);

const newSolutionNameSol = computed(() => store.state.newSolutionNameSol);
const newCustomerIDSol = computed(() => store.state.newCustomerIDSol);
const newCustomerSol = computed(() => store.state.newCustomerSol);
const newAssetNameSol = computed(() => store.state.newAssetNameSol);
const newLastViewSol = computed(() => store.state.newLastViewSol);
const newUserSol = computed(() => store.state.newUserSol);
const newTypeSol = computed(() => store.state.newTypeSol);
const newNotesSol = computed(() => store.state.newNotesSol);
const newDescriptionSol = computed(() => store.state.newDescriptionSol);

const newStepTodo = computed(() => solTodos.value.length);
const chosenSolId = computed(() => store.state.chosenSolutionId);
const customerChanged = computed(() => store.state.customerChanged);
const changedCustomerId = computed(() => store.state.changedCustomerId);

const darkMode = ref('');
const addRow = ref(false);
const configItemList = ref([]);
const solutions = ref([]);
const solTodos = ref([])
const sol = ref({})
const newAssetTodo = ref('');
const newTaskTodo = ref('');
const newCommentsTodo = ref('');
const newTodos = reactive([]);
const newRowId = computed(() => newTodos.length)

// delete new todo row
const deleteNewRow = () => {
    newAssetTodo.value = '';
    newTaskTodo.value = '';
    newCommentsTodo.value = '';
    addRow.value = false;
}

const deleteSolTodoFromNewTodos = (index) => {
    newTodos.splice(index, 1);
    newTodos.forEach((todo, i) => {
        todo.step = i
    })
}

// add new solution
const addSol = async () => {
    // check if all input data is valid
    if (newSolutionNameSol.value.trim() === "") {
        alert("Please add a solution name!");
        return;
    } else {
        var counter = 0;
        if (!(solutions.value.length == null)) {
            // check if solution name already exists
            solutions.value.forEach(s => {
                if (s.solutionName === newSolutionNameSol.value) {
                    counter += 1;
                }
            });
            if (counter == 1) {
                alert("This solution name already exists. Please choose an unique solution name or modify respectively delete the old one!");
                return;
            }
        }
    }
    if (newCustomerSol.value.length === 0) {
        alert("Please choose a customer!");
        return;
    }
    let allFine = true;
    newTodos.forEach(todo => {
        if (todo.asset.length === 0) {
            alert(`Please choose a config item for all todos.`);
            allFine = false
        }
    })
    if (!allFine) {
        return
    }
    try {
        const response = await Axios.post(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/addSol`,
            {
                solutionName: newSolutionNameSol.value,
                assetName: newAssetNameSol.value,
                customerID: newCustomerIDSol.value,
                customer: newCustomerSol.value,
                type: newTypeSol.value,
                lastView: newLastViewSol.value,
                user: newUserSol.value,
                description: newDescriptionSol.value,
                notes: newNotesSol.value,
            });
        store.commit('resetStore');
        store.commit('changeToSolutionlist');
        newTodos.forEach(async todo => {
            try {
                const res = await Axios.post(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/addTodoSol`,
                    {
                        solutionID: response.data,
                        step: todo.step,
                        asset: todo.asset,
                        task: todo.task,
                        comments: todo.comments,
                    });
            } catch (err) {
                console.log(err.response.statusText);
            }
        })
    } catch (err) {
        console.log(err.response.statusText);
    }
}

// add new row of todo for the new solution
const addRowForNewSol = async () => {
    if (newCustomerSol.value.length === 0) {
        alert("Please choose a customer first!");
        return;
    }
    await getConfigItemsFromCustomer();
    newTodos.push({
        solutionID: chosenSolId.value,
        step: newRowId.value,
        asset: '',
        task: '',
        comments: ''
    });
}

//update data
const updateSolTodo = async (todo) => {
    if (todo.asset.length === 0) {
        alert(`Please add the missing config item in row ${todo.step}!`);
        return;
    }
    try {
        await Axios.put(
            `https://${clientsideConfig.url}:${clientsideConfig.port}/api/updateSolTodo`,
            {
                primaryID: todo.primaryID,
                solutionID: todo.solutionIDID,
                step: todo.step,
                asset: todo.asset,
                task: todo.task,
                comments: todo.comments,
            }
        );
        await getSolutionById();
    } catch (err) {
        console.log(err.response.statusText);
    }
}

// add new solution todo
const addSolTodo = async () => {
    // check if all input data is valid
    if (newAssetTodo.value.length === 0) {
        alert("Please choose an asset for the new todo!");
        return;
    }
    try {
        const response = await Axios.post(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/addTodoSol`,
            {
                solutionID: chosenSolId.value,
                step: newStepTodo.value,
                asset: newAssetTodo.value,
                task: newTaskTodo.value,
                comments: newCommentsTodo.value,
            });
        addRow.value = false;
        await getSolutionTodosById();
        newAssetTodo.value = '';
        newTaskTodo.value = '';
        newCommentsTodo.value = '';
    } catch (err) {
        console.log(err.response.statusText);
    }
}

// add new row for the template
const addChecklistRow = async () => {
    await getConfigItemsFromCustomer();
    if (addRow.value) {
        alert('Please confirm the last added row first.')
        return
    }
    addRow.value = true
}

//get all solutions
const getAllSolutions = async () => {
    try {
        const response = await Axios.get(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/getAllSolutions`);
        solutions.value = response.data;
    } catch (err) {
        console.log(err.response.statusText);
    }
}

// include delay to avoid 503 error
const triggerBackendCallsWithDelay = async (fetchDataFunc) => {
    setTimeout(() => {
        fetchDataFunc();
    }, 1000);
}

// get solution todos from id
const getSolutionTodosById = async () => {
    if (!addBool.value) {
        try {
            const response = await Axios.get(
                `https://${clientsideConfig.url}:${clientsideConfig.port}/api/getTodosSolution/${chosenSolId.value}`
            );
            solTodos.value = response.data;
        } catch (err) {
            console.log(err.response.statusText);
        }
    }
}

//get all config items from the selected customer
const getConfigItemsFromCustomer = async () => {
    if (!addBool.value) {
        try {
            const response = await Axios.get(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/getCIFromCustomer/${sol.value.customerID}`);
            configItemList.value = response.data;
        } catch (err) {
            console.log(err.response.statusText);
        }
    } else {
        try {
            const response = await Axios.get(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/getCIFromCustomer/${changedCustomerId.value}`);
            configItemList.value = response.data;
        } catch (err) {
            console.log(err.response.statusText);
        }
    }
    if (customerChanged.value) {
        store.commit('toggleCustomerChanged');
    }
}

// get solution from id
const getSolutionById = async () => {
    if (!addBool.value) {
        try {
            const response = await Axios.get(
                `https://${clientsideConfig.url}:${clientsideConfig.port}/api/getSolution/${chosenSolId.value}`
            );
            sol.value = response.data;
        } catch (err) {
            console.log(err.response.statusText);
        }
    }
    await getConfigItemsFromCustomer();
}

const deleteSolTodo = async (id) => {
    if (confirm("Do you really want to delete this solution todo? It cannot be undone!")) {
        try {
            await Axios.delete(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/deleteSolTodo/${id}`);
        } catch (err) {
            console.log(err.response.statusText);
        }
    }
    await getSolutionTodosById();
}

const getSession = async () => {
    const loggedInUserDarkModeBool = getItem('logged-in-user-darkMode');
    if (loggedInUserDarkModeBool == 1) {
        darkMode.value = true;
    } else {
        darkMode.value = false;
    }
}

function getItem(item) {
    if (process.client) {
        return localStorage.getItem(item)
    } else {
        return undefined
    }
}

watch(customerChanged, getSolutionById);
watch(modeChanged, getSession)

onMounted(async () => {
    getSession();
    await getSolutionTodosById();
    await getSolutionById();
    triggerBackendCallsWithDelay(getAllSolutions);
});
</script>

<script>
export default {
    name: "SolutionChecklist",
};
</script>


<style scoped>
.data {
    display: flex;
    flex-direction: row;
    align-items: flex-start;
    align-self: stretch;
    padding: 0 0.625rem;
    border-radius: 0.3125rem;
    box-shadow: 0.0625rem 0.0625rem 0.25rem 0rem rgba(0, 0, 0, 0.25) inset;
    letter-spacing: 5%;
    font: 400 0.75rem/250% Overpass, sans-serif;
}

.saveSolTodos-darkmode {
    background: #212121;
    color: #fff;
    font: 400 0.875rem/1.875rem Overpass, sans-serif;
    border: none;
    border-radius: 0.625rem;
    margin-left: 10rem;
    padding-left: 0.9rem;
    padding-right: 0.9rem;
}

.saveSolTodos-lightmode {
    background: #EBEBEB;
    color: #212121;
    font: 400 0.875rem/1.875rem Overpass, sans-serif;
    border: none;
    border-radius: 0.625rem;
    margin-left: 10rem;
    padding-left: 0.9rem;
    padding-right: 0.9rem;
}

.saveNewSol-darkmode {
    background: #2c2c2c;
    color: #fff;
    font: 400 0.875rem/1.875rem Overpass, sans-serif;
    border: none;
    padding: 1rem 1.875rem;
    width: 8%;
    border-radius: 0.625rem;
    box-shadow: 0.25rem 0.25rem 0.25rem 0rem rgba(0, 0, 0, 0.25);
}

.saveNewSol-lightmode {
    background: #EBEBEB;
    color: #212121;
    font: 400 0.875rem/1.875rem Overpass, sans-serif;
    border: none;
    padding: 1rem 1.875rem;
    width: 8%;
    border-radius: 0.625rem;
    box-shadow: 0.25rem 0.25rem 0.25rem 0rem rgba(0, 0, 0, 0.25);
}

.deleteSolTodos-darkmode {
    background: #212121;
    color: #fff;
    font: 400 0.875rem/1.875rem Overpass, sans-serif;
    border: none;
    border-radius: 0.625rem;
    margin-left: 15.8rem;
    padding-left: 0.9rem;
    padding-right: 0.9rem;
}

.deleteLastSolTodos-darkmode {
    background: #212121;
    color: #fff;
    font: 400 0.875rem/1.875rem Overpass, sans-serif;
    border: none;
    border-radius: 0.625rem;
    margin-left: 2rem;
    padding-left: 0.9rem;
    padding-right: 0.9rem;
}

.deleteSolTodos-lightmode {
    background: #EBEBEB;
    color: #212121;
    font: 400 0.875rem/1.875rem Overpass, sans-serif;
    border: none;
    border-radius: 0.625rem;
    margin-left: 15.8rem;
    padding-left: 0.9rem;
    padding-right: 0.9rem;
}

.deleteLastSolTodos-lightmode {
    background: #EBEBEB;
    color: #212121;
    font: 400 0.875rem/1.875rem Overpass, sans-serif;
    border: none;
    border-radius: 0.625rem;
    margin-left: 2rem;
    padding-left: 0.9rem;
    padding-right: 0.9rem;
}

.input {
    border: none;
}

.div-darkmode {
    background-color: #2c2c2c;
}

.div-lightmode {
    background-color: #fff;
}

.data-darkmode {
    background-color: #212121;
    color: #fff;
}

.data-lightmode {
    background-color: #EBEBEB;
    color: #000;
}

.data-table {
    width: 100%;
    padding: 0 0.625rem;
    table-layout: fixed;
    border-collapse: collapse;
}

.solution-checklist-information {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: center;
    padding: 1.25rem 1.875rem;
    border-radius: 0.625rem;
    box-shadow: 0.25rem 0.25rem 0.25rem 0rem rgba(0, 0, 0, 0.25);
}

.section-darkmode {
    background-color: #2c2c2c;
}

.section-lightmode {
    background-color: #fff;
}

.table-row {
    display: flex;
    flex-direction: row;
    align-items: center;
    height: 3.125rem;
    padding: 0.625rem;
    gap: 0.625rem;
}

.select-darkmode {
    border: none;
    color: white;
    background: #212121;
    padding: 0.4rem;
    border-radius: 0.3125rem;
}

.select-lightmode {
    border: none;
    color: black;
    background: #EBEBEB;
    padding: 0.4rem;
    border-radius: 0.3125rem;
}

.tr-head-darkmode {
    border-top: none;
    border-bottom: 0.0625rem solid #000000;
}

.tr-head-lightmode {
    border-top: none;
    border-bottom: 0.0625rem solid #8e8e8e;
}

.tr-darkmode {
    border-top: 0.0625rem solid #000000;
}

.tr-lightmode {
    border-top: 0.0625rem solid #8e8e8e;
}

th,
td {
    height: 1.875rem;
    text-align: left;
    padding: 0;
    letter-spacing: 5%;
    font: 400 0.875rem/1.875rem Overpass, sans-serif;
}

th {
    font: 700 0.875rem/1.875rem Overpass, sans-serif;
}

.th-darkmode,
.td-darkmode {
    color: #ffffff;
}

.th-lightmode,
.td-lightmode {
    color: #000;
}

.Step {
    width: 8%;
}

.Step-darkmode {
    border-right: 0.0625rem solid #000000;
}

.Step-lightmode {
    border-right: 0.0625rem solid #8e8e8e;
}

.Asset {
    width: 22%;
}

.Asset-darkmode {
    border-right: 0.0625rem solid #000000;
}

.Asset-lightmode {
    border-right: 0.0625rem solid #8e8e8e;
}

.Task {
    width: 35%;
}

.Task-darkmode {
    border-right: 0.0625rem solid #000000;
}

.Task-lightmode {
    border-right: 0.0625rem solid #8e8e8e;
}

.Comments {
    width: 35%;
    display: flex;
}

.label {
    width: 6.0625em;
    height: 1.875em;
    font-family: 'Overpass';
    font-style: normal;
    font-weight: 400;
    font-size: 1em;
    line-height: 1.875em;
    letter-spacing: 0.05em;
}

.label-darkmode {
    color: #FFFFFF;
}

.label-lightmode {
    color: #000;
}

.editSolTodos-darkmode {
    background: #2c2c2c;
    color: #fff;
    font: 400 0.875rem/1.875rem Overpass, sans-serif;
    border: none;
    padding: 0.825rem 0.7rem;
    width: 4%;
    border-radius: 0.625rem;
    box-shadow: 0.25rem 0.25rem 0.25rem 0rem rgba(0, 0, 0, 0.25);
}

.editSolTodos-lightmode {
    background: #EBEBEB;
    color: #212121;
    font: 400 0.875rem/1.875rem Overpass, sans-serif;
    border: none;
    margin-left: 15rem;
    padding-left: 0.9rem;
    padding-right: 0.9rem;
    border-radius: 0.625rem;
}

.deleteSolTodos-darkmode:hover,
.deleteLastSolTodos-darkmode:hover,

.saveSolTodos-darkmode:hover,
.editSolTodos-darkmode:hover,
.saveNewSol-darkmode:hover {
    background-color: #444444;
    cursor: pointer;
}

.deleteSolTodos-lightmode:hover,
.deleteLastSolTodos-lightmode:hover,

.saveSolTodos-lightmode:hover,
.editSolTodos-lightmode:hover,
.saveNewSol-lightmode:hover {
    background-color: #ACACAC;
    cursor: pointer;
}

#saveNewSol {
    text-align: center;
}

#editSolTodos {
    text-align: right;
}
</style>