<template>
  <div class="routes-modal" v-if="store.currentStation">
    <div class="exit" @click="closeRoutesModal">
      <img src="/icon-exit.svg" alt="exit icon" />
    </div>

    <div class="modal-wrapper">
      <h1>Szlaki na scenerii {{ store.currentStation.name }}</h1>

      <ul class="route-list">
        <li class="route" v-for="(route, i) in computedRouteList" :key="route.routeName + i">
          <img @click="removeRoute(i)" class="route-delete" src="/icon-trash.svg" alt="icon trash" />

          <form>
            <div>Szlak: <input type="text" v-model="route.routeName" /></div>
            <div>
              <input
                type="checkbox"
                :name="`${route.routeName}-internal`"
                :id="`${route.routeName}-internal`"
                v-model="route.routeIsInternal"
              />
              <label :for="`${route.routeName}-internal`">Szlak wewnętrzny</label>
            </div>

            <div>
              <span>Liczba torów: </span>
              <input
                type="radio"
                :name="`${route.routeName}-tracks`"
                :id="`${route.routeName}-track1`"
                :value="Number(1)"
                :checked="route.routeTracks == 1"
                v-model="route.routeTracks"
              />
              <label :for="`${route.routeName}-track1`">1</label>

              <input
                type="radio"
                :name="`${route.routeName}-tracks`"
                :id="`${route.routeName}-track2`"
                :value="Number(2)"
                :checked="route.routeTracks == 2"
                v-model="route.routeTracks"
              />
              <label :for="`${route.routeName}-track2`">2</label>
            </div>
            <div>
              <span>Elektryfikacja: </span>

              <input
                type="radio"
                :name="`${route.routeName}-electr`"
                :id="`${route.routeName}-E`"
                :checked="route.routeElectrification == 'E'"
                value="E"
                v-model="route.routeElectrification"
              />
              <label :for="`${route.routeName}-E`">Tak</label>

              <input
                type="radio"
                :name="`${route.routeName}-electr`"
                :id="`${route.routeName}-N`"
                :checked="route.routeElectrification == 'N'"
                value="N"
                v-model="route.routeElectrification"
              />
              <label :for="`${route.routeName}-N`">Nie</label>
            </div>
            <div>
              <span>Typ blokady: </span>

              <input
                type="radio"
                :name="`${route.routeName}-block`"
                :id="`${route.routeName}-PBL`"
                :checked="route.routeBlockType == 'P'"
                value="P"
                v-model="route.routeBlockType"
              />
              <label :for="`${route.routeName}-PBL`">PBL</label>

              <input
                type="radio"
                :name="`${route.routeName}-block`"
                :id="`${route.routeName}-SBL`"
                :checked="route.routeBlockType == 'S'"
                value="S"
                v-model="route.routeBlockType"
              />
              <label :for="`${route.routeName}-SBL`">SBL</label>
            </div>

            <div>
              <span>Blokada dwukierunkowa: </span>

              <input
                type="radio"
                :name="`${route.routeName}-2twb`"
                :id="`${route.routeName}-twb`"
                :checked="route.routeHasTwoWayBlock"
                :value="true"
                v-model="route.routeHasTwoWayBlock"
              />
              <label :for="`${route.routeName}-twb`">Tak</label>

              <input
                type="radio"
                :name="`${route.routeName}-2twb`"
                :id="`${route.routeName}-notwb`"
                :checked="!route.routeHasTwoWayBlock"
                :value="false"
                v-model="route.routeHasTwoWayBlock"
              />
              <label :for="`${route.routeName}-notwb`">Nie</label>
            </div>
          </form>
        </li>
      </ul>
    </div>

    <div class="routes-actions">
      <button @click="saveRoutes">Zapisz</button>
      <button @click="addNewRoute">Dodaj szlak</button>
      <button @click="closeRoutesModal">Zamknij</button>
    </div>
  </div>
</template>

<script lang="ts">import { defineComponent } from 'vue';
import changeMixin from '../mixins/changeMixin';
import { useStore } from '../store';


export default defineComponent({
  setup() {
    return {
      store: useStore(),
    };
  },

  mixins: [changeMixin],

  data: () => ({
    currentRoutes: '',
    routeBackup: '',
  }),

  computed: {
    computedRouteList() {
      if (!this.store.currentStation) return [];

      if (this.currentRoutes.length == 0) return [];

      return this.currentRoutes.split(';').map((route) => {
        /*
          Route: !Oc_2EPB
          ! - szlak wewnętrzny (! - tak, brak wykrzyknika - nie)
          Oc - nazwa scenerii
          2 - liczba torów (1 lub 2)
          E - elektryfikacja (E - tak, N - nie)
          P - rodzaj blokady (P - PBL, S - SBL)
          B - blokada dwukierunkowa (B - tak, brak litery - nie)
        */
        const routeProps = route.split('_');
        const routeIsInternal = routeProps[0].startsWith('!');
        const routeName = routeIsInternal ? routeProps[0].replace('!', '') : routeProps[0];

        const routeSpecs = routeProps[1];
        return {
          routeName,
          routeTracks: Number(routeSpecs[0]),
          routeElectrification: routeSpecs[1],
          routeBlockType: routeSpecs[2],
          routeHasTwoWayBlock: routeSpecs[3] ? true : false,
          routeIsInternal,
        };
      });
    },
  },

  mounted() {
    if (this.store.currentStation) {
       this.currentRoutes = this.store.currentStation.routes;
       this.routeBackup = this.currentRoutes;
    }
    // console.log(this.currentRoutes + " git");
    
  },

  methods: {
    closeRoutesModal() {
      this.store.currentStation = null;
      this.currentRoutes = '';
    },

    addNewRoute() {
      this.currentRoutes += (this.currentRoutes.length != 0 ? ';' : '') + `-_1EP`;
      this.saveRoutes();
    },

    removeRoute(index: number) {
      this.currentRoutes = this.currentRoutes
        .split(';')
        .filter((_, i) => i != index)
        .join(';');

      this.saveRoutes();
    },

    saveRoutes() {
      const index = this.store.stationList.findIndex((station) => station.name === this.store.currentStation?.name);

      if (index == -1) return;

      const routeString = this.computedRouteList
        .map(
          (route) =>
            `${route.routeIsInternal ? '!' : ''}${route.routeName.trim()}_${route.routeTracks}${
              route.routeElectrification
            }${route.routeBlockType}${route.routeHasTwoWayBlock ? 'B' : ''}`
        )
        .join(';');

      this.store.stationList[index]['routes'] = routeString;
      this.currentRoutes = routeString;

      this.addChange(this.store.currentStation!, 'routes', this.routeBackup, routeString);
    },
  },
});
</script>

<style lang="scss" scoped>
.routes-modal {
  position: fixed;
  top: 50%;
  left: 50%;

  width: 90%;
  max-width: 800px;

  height: 95%;
  overflow: hidden;
  padding: 0.5em 0;

  display: flex;
  flex-direction: column;

  transform: translate(-50%, -50%);
  z-index: 100;

  background-color: #333;
}

.modal-wrapper {
  overflow: auto;
  flex-grow: 2;
}

.routes-modal h1 {
  position: sticky;
  top: 0;

  z-index: 100;

  background-color: #333;
  padding: 0.5em 2em;

  text-align: center;
}

.routes-modal label {
  padding: 0;
}

.routes-modal .exit {
  position: absolute;
  top: 0;
  right: 0;
  z-index: 101;

  cursor: pointer;
  margin: 0.5em 1.5em;
}

.exit img {
  width: 2.5em;
}

.routes-modal input {
  display: inline;
  padding: 0;
  margin: 0.5em 0;

  color: black;
  font-size: 1em;

  max-width: 120px;
}

ul {
  list-style: none;
  padding: 0 1em;
  margin: 0;
}

ul li {
  padding: 0.65em;
  margin: 0.5em 0;

  position: relative;

  background-color: #222;
}

.route-delete {
  position: absolute;
  top: 0;
  right: 0;
  margin: 0.5em;
  width: 1.15em;

  cursor: pointer;
}

.routes-actions {
  background-color: #333;
  width: 100%;

  margin-top: 0.5em;
  padding: 0.5em 0;
  text-align: center;
}

.routes-actions button {
  font-size: 1.2em;
}
</style>
