<template>
  <b-container fluid>
    <b-row>
      <b-col md="5">
        <h2>Scratchpad</h2>
        <ScratchPad />
      </b-col>
      <b-col md="5">

        <div>
          <b-tabs content-class="mt-3" v-model="tabIndex">
            <b-tab active>
                <template v-slot:title>
                  Editor <span v-bind:class="{ dirty: isDirty, clean: !isDirty }">&bull;</span>
                </template>
              <MainEditor :slug="$route.params.slug" @markDirty="markDirty"/>
            </b-tab>
            <b-tab title="Viewer">
              <MainView :slug="$route.params.slug" />
            </b-tab>
          </b-tabs>
        </div>


      </b-col>
      <b-col md="2">
        <h2>Search Results</h2>
        <SearchResults :editMode="true" target="console-slug" />
      </b-col>
    </b-row>
  </b-container>
</template>

<script>
// @ is an alias to /src
import MainEditor from "../components/MainEditor";
import MainView from "../components/MainView";
import ScratchPad from "../components/ScratchPad";
import SearchResults from "../components/Search";

export default {
  name: 'home',
  components: {
    SearchResults,
    ScratchPad,
    MainEditor,
    MainView
  },
  data: function() {
    return {
      isDirty: false,
      tabIndex: 0
    }
  },
  methods: {
    markDirty: function(dirty) {
      this.isDirty = dirty
    }
  },
  beforeRouteEnter (to, from, next) {
    // called before the route that renders this component is confirmed.
    // does NOT have access to `this` component instance,
    // because it has not been created yet when this guard is called!
    next()
  },
  beforeRouteUpdate (to, from, next) {
    // called when the route that renders this component has changed,
    // but this component is reused in the new route.
    // For example, for a route with dynamic params `/foo/:id`, when we
    // navigate between `/foo/1` and `/foo/2`, the same `Foo` component instance
    // will be reused, and this hook will be called when that happens.
    // has access to `this` component instance.
    if (this.isDirty) {
      const answer = window.confirm('Do you really want to leave? you have unsaved changes!')
      if (answer) {
        next()
      } else {
        next(false)
      }
    }
    this.tabIndex = 0
    next()
  },
  beforeRouteLeave (to, from, next) {
    // called when the route that renders this component is about to
    // be navigated away from.
    // has access to `this` component instance.
    next()
  }
}
</script>

<style scoped>
  h2 {
    font-size: large;
  }
  .dirty {
    color: red;
  }
  .clean {
      display: none;
  }
</style>
