<template>
  <div class="page-container">
    <header>
      <div>logo</div>
      <div>
        <div v-show="!isPickerVisible">
          tap an airport on the map, or&nbsp;
          <button class="btn btn--primary" @click="showPicker">
            search here
          </button>
        </div>
        <div v-show="isPickerVisible">
          <button class="btn btn--primary" @click="showPicker">
            hide search
          </button>
        </div>
      </div>
    </header>
    <!-- <pre style="position: fixed; z-index: 500; right: 0; top: 2rem; font-size: 0.6rem; color: gray;">
      {{ selectedOrig }}
      {{ selectedDest }}
    </pre> -->
    <main>
      <aside v-show="isPickerVisible" class="nav">
        <AirportPicker
          :airports="airports_orig"
          :selected-airport="selectedOrig"
          @select-airport="makeOrigin"
          @deselect-airport="clearOrigin"
        />
        <AirportPicker
          v-show="selectedOrig.iata"
          :airports="airports_dest"
          :selected-airport="selectedDest"
          @select-airport="makeDestination"
          @deselect-airport="clearDestination"
        />
      </aside>
      <Map
        :airports-orig="airports_orig"
        :airports-dest="airports_dest"
        :selected-orig="selectedOrig"
        :selected-dest="selectedDest"
        @make-origin="makeOrigin"
        @make-destination="makeDestination"
        @clear-origin="clearOrigin"
        @clear-destination="clearDestination"
      />
    </main>
  </div>
</template>

<script>
import AirportPicker from '../components/AirportPicker.vue'
export default {
  components: { AirportPicker },
  data () {
    return {
      color: 'red',
      mountains: [
        {
          slug: 'sluggy',
          title: 'titly'
        }
      ],
      isPickerVisible: false,
      airports_orig: [],
      airports_dest: [],
      airportFetch_filterFormula: 'AND(Is_Origin=1,{IsCurrent-AsOrigin}=\'Yes\')',
      airportFetch_fields: [
        'Airport_IATA',
        'Icon_Url',
        'Latitude_Deg',
        'Longitude_Deg',
        'Municipality',
        'Airport_Name',
        'Type',
        'Search_Field'
      ],
      airportFetch_sort: '&sort[0][field]=Airport_IATA&sort[0][direction]=asc',
      selectedOrig: {
        iata: '',
        lat: '',
        long: '',
        icon: '',
        name: '',
        municipality: '',
        type: '',
        search: ''
      },
      selectedDest: {
        iata: '',
        lat: '',
        long: '',
        icon: '',
        name: '',
        municipality: '',
        type: '',
        search: ''
      },
      emptyAirport: {
        iata: '',
        lat: '',
        long: '',
        icon: '',
        name: '',
        municipality: '',
        type: '',
        search: ''
      }
    }
  },
  async fetch () {
    this.mountains = await fetch(
      'https://api.nuxtjs.dev/mountains'
    ).then(res => res.json())

    let response2 = {}
    let mapData2 = {}

    const response = await fetch(`https://api.airtable.com/v0/appiQwfVZixRgRICe/Airports_IATA?filterByFormula=${this.airportFetch_filterFormula}${this.airportFetch_fields_string}${this.airportFetch_sort}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        Authorization: 'Bearer keyJ2ht64ZSN57AG1'
      }
    })

    if (await response.offset) {
      response2 = fetch(`https://api.airtable.com/v0/appiQwfVZixRgRICe/Airports_IATA?filterByFormula=${this.airportFetch_filterFormula}&fields[]=Airport_IATA&fields[]=Icon_Url&fields[]=Latitude_Deg&fields[]=Longitude_Deg&sort[0][field]=Airport_IATA&sort[0][direction]=asc&offset=${response.offset}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          Authorization: 'Bearer keyJ2ht64ZSN57AG1'
        }
      })
      mapData2 = await response2.json()
    }

    const mapData = await response.json()

    const r1 = mapData.records
    const r2 = mapData2.records

    console.log(r2)

    // const mapDataTotal = [...r1, ...r2]

    const mapDataTotal = [...r1]

    this.airports_orig = mapDataTotal.map((record) => {
      return {
        iata: record.fields.Airport_IATA,
        lat: record.fields.Latitude_Deg,
        long: record.fields.Longitude_Deg,
        icon: record.fields.Icon_Url,
        name: record.fields.Airport_Name,
        municipality: record.fields.Municipality,
        type: record.fields.Type,
        search: record.fields.Search_Field
      }
    })
  },
  computed: {
    airportFetch_fields_string () {
      const vm = this
      const array = vm.airportFetch_fields.map((field) => {
        return '&fields[]=' + field
      })
      return array.join('')
    }
  },
  methods: {
    makeOrigin (airport) {
      // console.log(airport)

      this.selectedOrig = { ...airport }

      this.selectedDest = { ...this.emptyAirport }

      // this.$router.push('/go/' + airport.iata)

      history.pushState(
        {},
        null,
        this.$route.path + encodeURIComponent(airport.iata)
      )

      this.fetchDestinations(airport.iata, this)
    },
    makeDestination (airport) {
      this.selectedDest = { ...airport }
      // this.$router.push('/go/' + this.selectedOrig.iata + '/' + airport.iata)

      history.pushState(
        {},
        null,
        this.$route.path + encodeURIComponent(this.selectedOrig.iata) + '/' + encodeURIComponent(airport.iata)
      )
    },
    clearOrigin () {
      this.selectedOrig = { ...this.emptyAirport }
      this.selectedDest = { ...this.emptyAirport }
      history.pushState(
        {},
        null,
        this.$route.path
      )
    },
    clearDestination () {
      this.selectedDest = { ...this.emptyAirport }
      history.pushState(
        {},
        null,
        this.$route.path + encodeURIComponent(this.selectedOrig.iata)
      )
    },
    async fetchDestinations (iata) {
      const airportFetchDestfilterFormula = `AND(Is_Destination=1,{IsCurrent-AsDest}="Yes",(FIND("${iata}", Associated_Origin_Search)>0))`

      const response = await fetch(`https://api.airtable.com/v0/appiQwfVZixRgRICe/Airports_IATA?filterByFormula=${airportFetchDestfilterFormula}${this.airportFetch_fields_string}${this.airportFetch_sort}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          Authorization: 'Bearer keyJ2ht64ZSN57AG1'
        }
      })

      const mapData = await response.json()

      // console.log('mapData.records length: ' + mapData.records.length)
      // console.log('this.airports_dest length (before): ' + this.airports_dest.length)

      this.color = 'fetchDestinations'
      this.airports_dest = mapData.records.map((record) => {
        return {
          iata: record.fields.Airport_IATA,
          lat: record.fields.Latitude_Deg,
          long: record.fields.Longitude_Deg,
          icon: record.fields.Icon_Url,
          name: record.fields.Airport_Name,
          municipality: record.fields.Municipality,
          type: record.fields.Type,
          search: record.fields.Search_Field
        }
      })

      // this.$refs.flMap.mapObject.fitBounds(this.markers.map((m) => { return [m.lat, m.lng] }))

      // console.log('this.airports_dest length (after)' + this.airports_dest.length)
    },
    showPicker () {
      this.isPickerVisible = !this.isPickerVisible
    }
  }
}
</script>

<style>
html,
body,
#__nuxt,
#__layout,
.page-container,
main {
  height: 100%;
}

header {
  position: fixed;
  top: 0;
  width: 100vw;
  z-index: 402;
  display: flex;
  flex-direction: row;
  padding: 1rem;
}

main {
  display: flex;
  flex-direction: column;

  /* grid-template-rows: min-content 1fr; */
}

.nav {
  flex: 0 0 auto;

  /* position: fixed;
  top: 0;
  padding-top: 4rem;
  width: 100vw;
  z-index: 401; */
  background: white;
  display: flex;
  flex-direction: column;
  justify-items: center;
  margin-top: 3.5rem;
}

.btn--nav-open {
  padding: 1rem;
  display: block;
}
</style>
