<template>
  <section v-if="!addBool" :class="['information', darkMode ? 'section-darkmode' : 'section-lightmode']">
    <h2 v-if="!editable" :class="['department-name', darkMode ? 'h2-darkmode' : 'h2-lightmode']">{{ dep.name
      }}</h2>
    <input v-if="editable" v-model="dep.name" @change="updateDepartment()"
      :class="['data', 'department-name-input', darkMode ? 'h2-darkmode' : 'h2-lightmode', darkMode ? 'h2-input-darkmode' : 'h2-input-lightmode', 'input']">
    <div class="data-group">
      <div class="data-field" id="id">
        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">ID:</pre>
        <pre :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ dep.primaryID }}</pre>
      </div>
      <div class="data-field" id="customer-id">
        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Customer:</pre>
        <pre :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ dep.customername }}</pre>
      </div>
      <div class="data-field" id="head">
        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Head:</pre>
        <pre v-if="!editable" :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ dep.head }}</pre>
        <input v-if="editable" v-model="dep.head" @change="updateDepartment()"
          :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
      </div>
    </div>
    <div class="notes">
      <pre :class="['area-title', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Notes:</pre>
      <input v-model="dep.notes" :readonly="!editable" @change="updateDepartment()"
        :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']" id="notes">
    </div>
  </section>
  <section v-if="addBool" :class="['information', darkMode ? 'section-darkmode' : 'section-lightmode']">
    <input v-model="newName"
      :class="['data', 'department-name-input', darkMode ? 'h2-darkmode' : 'h2-lightmode', darkMode ? 'h2-input-darkmode' : 'h2-input-lightmode', 'input']">
    <div class="data-group">
      <div class="data-field" id="id">
        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">ID:</pre>
        <pre :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">...</pre>
      </div>
      <div class="data-field" id="customer-id">
        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Customer:</pre>
        <pre :class="['data', darkMode ? 'data-darkmode' : 'data-lightmode']">{{ chosenCustomerId }}</pre>
      </div>
      <div class="data-field" id="head">
        <pre :class="['label', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Head:</pre>
        <input v-model="newHead"
          :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']">
      </div>
    </div>
    <div class="notes">
      <pre :class="['area-title', darkMode ? 'pre-darkmode' : 'pre-lightmode']">Notes:</pre>
      <input v-model="newNotes"
        :class="['data', 'input', darkMode ? 'data-darkmode' : 'data-lightmode']" id="notes">
    </div>
  </section>
  <section v-if="addBool" id="saveNewItem">
    <button :class="[darkMode ? 'saveNewItem-darkmode' : 'saveNewItem-lightmode']" @click="addDepartment()">Save</button>
  </section>
</template>



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

const store = useStore();
const modeChanged = computed(() => store.state.updateDarkMode);
const editable = computed(() => store.state.editable);
const chosenCustomerId = computed(() => store.state.chosenCustomerId);
const chosenDepartmentId = computed(() => store.state.chosenDepartmentId);
const deleteBool = computed(() => store.state.deleteBool);
const addBool = computed(() => store.state.new);
const darkMode = ref('')
const dep = ref({});
const departments = ref({});
const customer = ref({});

const newName = ref('');
const newHead = ref('');
const newNotes = ref('');

// get department from id
const getDepartmentById = async () => {
  if (!addBool.value) {
    try {
      const response = await Axios.get(
        `https://${clientsideConfig.url}:${clientsideConfig.port}/api/getDepartment/${chosenDepartmentId.value}`
      );
      dep.value = response.data;
    } catch (err) {
      console.log(err.response.statusText);
    }
  }
}

//update data
const updateDepartment = async () => {
  if (dep.value.name.trim() === "") {
    alert("Please add a department name!");
    return;
  } else {
    var counter = 0;
    // check if department name already exists
    departments.value.forEach(d => {
      if (d.name === dep.value.name) {
        counter += 1;
      }
    });
    if (counter == 2) {
      alert("This department name already exists. Please choose an unique department name or modify respectively delete the old one!");
      dep.value.name = '';
      return;
    }
    try {
      await Axios.put(
        `https://${clientsideConfig.url}:${clientsideConfig.port}/api/updateDepartment`,
        {
          primaryID: dep.value.primaryID,
          name: dep.value.name,
          head: dep.value.head,
          notes: dep.value.notes,
        }
      )
      await getDepartmentById();
    } catch (err) {
      console.log(err.response.statusText);
    }
  }
}

// add new department
const addDepartment = async () => {
  // check if all input data is valid
  if (newName.value.trim() === "") {
    alert("Please add an department name!");
    return;
  } else {
    var counter = 0;
    // check if department name already exists
    departments.value.forEach(c => {
      if (c.name === newName.value) {
        counter += 1;
      }
    });
    if (counter == 1) {
      alert("This department name already exists. Please choose an unique department name or modify respectively delete the old one!");
      return;
    }
  }
  try {
    const response = await Axios.post(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/addDepartment`,
      {
        customerID: chosenCustomerId.value,
        customername: customer.value.customername,
        name: newName.value,
        head: newHead.value,
        notes: newNotes.value,
      });
    store.commit('resetStoreNotCustomer');
    store.commit('changeToDepartmentlist');
  } catch (err) {
    console.log(err.response.statusText);
  }
}

// get customer from id
const getCustomerById = async () => {
  try {
    const response = await Axios.get(
      `https://${clientsideConfig.url}:${clientsideConfig.port}/api/getCustomerById/${chosenCustomerId.value}`
    );
    customer.value = response.data;
  } catch (err) {
    console.log(err.response.statusText);
  }
}


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

const confirmDeleteDepartment = async () => {
    if (deleteBool.value === true) {
        if (confirm("Do you really want to delete this department? It cannot be undone!")) {
            try {
                await Axios.delete(`https://${clientsideConfig.url}:${clientsideConfig.port}/api/deleteDepartment/${chosenDepartmentId.value}`);
            } catch (err) {
                console.log(err.response.statusText);
            }
            store.commit('undoDelete');
            store.commit('resetStoreNotCustomer');
            store.commit('changeToDepartmentlist');
        } else {
            store.commit('undoDelete');
        }
    }
}

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

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(modeChanged, getSession);
watch(deleteBool, confirmDeleteDepartment);

onMounted(async () => {
  getSession();
  await getDepartmentById();
  triggerBackendCallsWithDelay(getCustomerById);
  triggerBackendCallsWithDelay(getDepartments);
});
</script>

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



<style scoped>
* {
  box-sizing: border-box;
  margin: 0;
}

.information {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: center;
  width: 100%;
  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: #ffffff;
}

.input {
  border: none;
}

.department-name-input {
  padding: 1rem 0;
  margin: 1rem;
  font-size: initial;
  letter-spacing: 5%;
  text-decoration-line: underline;
  font: italic 400 1rem/187.5% Overpass, -apple-system, Roboto, Helvetica,
    sans-serif;
}

.department-name {
  align-self: stretch;
  padding: 1rem 0;
  letter-spacing: 5%;
  text-decoration-line: underline;
  font: italic 400 1rem/187.5% Overpass, -apple-system, Roboto, Helvetica,
    sans-serif;
}

.h2-darkmode {
  color: #fff;
}

.h2-lightmode {
  color: #000;
}

.h2-input-darkmode {
  background-color: #212121;
}

.h2-input-lightmode {
  background-color: #EBEBEB;
}

.data-group {
  display: flex;
  flex: auto;
  width: 100%;
  flex-direction: row;
  padding: 0.625rem 0;
  align-items: center;
  justify-content: stretch;
}


.data-field {
  display: flex;
  flex: auto;
  width: 30%;
  flex-direction: row;
  padding: 0.8rem 1.875rem;
  align-items: center;
  justify-content: flex-start;
  gap: 1.25rem;
}

#head {
  width: 40%;
}

.label {
  letter-spacing: 0.02rem;
  font: 400 0.875rem/1.875rem Overpass, sans-serif;
}

.pre-darkmode {
  color: #ffffff;
}

.pre-lightmode {
  color: #000000;
}

.data {
  display: flex;
  flex-direction: row;
  padding: 0 0.625rem;
  border-radius: 0.3125rem;
  box-shadow: 0.0625rem 0.0625rem 0.25rem 0rem rgba(0, 0, 0, 0.25) inset;
  background-color: #212121;
  align-items: center;
  justify-content: flex-start;
  letter-spacing: 0.02rem;
  font: 400 0.75rem/1.875rem Overpass, sans-serif;
}

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

.data-lightmode {
  background-color: #ebebeb;
  color: #000000;
}


.notes {
  display: flex;
  flex: auto;
  flex-direction: column;
  padding: 1.25rem 1.875rem 0.625rem;
  align-items: flex-start;
  justify-content: center;
  gap: 0.625rem;
  width: 50%;
}

.area-title {
  letter-spacing: 0.03rem;
  font: 400 0.875rem/1.875rem Overpass, sans-serif;
}

#notes {
  align-self: stretch;
}

.saveNewItem-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);
}

.saveNewItem-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);
}

.saveNewItem-darkmode:hover {
  background-color: #444444;
  cursor: pointer;
}

.saveNewItem-lightmode:hover {
  background-color: #ACACAC;
  cursor: pointer;
}

#saveNewItem {
  text-align: center;
}
</style>