<template>
  <div class="white-bkg">
    <header>
      <div class="header__col">
        <button class="btn btn--primary" @click="goBack">
          <svg
            xmlns="http://www.w3.org/2000/svg"
            class="icon icon-tabler icon-tabler-chevrons-left"
            width="24"
            height="24"
            viewBox="0 0 24 24"
            stroke-width="3"
            stroke="#ffffff"
            fill="none"
            stroke-linecap="round"
            stroke-linejoin="round"
          >
            <path stroke="none" d="M0 0h24v24H0z" fill="none" />
            <polyline points="11 7 6 12 11 17" />
            <polyline points="17 7 12 12 17 17" />
          </svg> back
        </button>
      </div>
      <div class="header__col">
        <Logo />
      </div>
      <div class="header__col" />
    </header>
    <main class="main-with-header">
      <ChosenFlights
        :selected-orig="selectedOrig"
        :selected-dest="selectedDest"
        style="margin: 0 1rem;"
      />
      <!-- <pre>
        {{ schedules }}
      </pre> -->
      <DatePicker
        :starting-date="startingDate"
        :selected-dows="selectedDows"
      />
    </main>
  </div>
</template>

<script>
export default {
  data () {
    return {
      schedules: [],
      startingDate: new Date(),
      selectedSchedule: {},
      selectedDays: [],
      selectedOrig: {},
      selectedDest: {}
    }
  },
  async fetch () {
    // console.log(this.$route.params.o)

    const today = new Date().toLocaleDateString('en-CA')

    // function addDays (date, days) {
    //   const result = new Date(date)
    //   result.setDate(result.getDate() + days)
    //   return result
    // }

    // const tomorrow = addDays(new Date(), 1).toLocaleDateString('en-CA')

    const scheduleFetchFilterFormula = `AND(Is_Current="Yes",Origin_IATA="${this.$route.params.o}",Destination_IATA="${this.$route.params.d}",Effective_End>"${today}")`
    const scheduleFetchSort = '&sort[0][field]=Departure_TimeL&sort[0][direction]=asc'

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

    const data = await response.json()

    // console.log(data)

    this.schedules = [...data.records]
  },
  computed: {
    selectedDows () {
      const mappedDows = this.schedules.map((schedule) => {
        // console.log(schedule.fields)
        return {
          Flight_Number: schedule.fields.Flight_Number,
          DowsList: this.daysList(schedule.fields.Frequency_Convert),
          Effective_Start: schedule.fields.Effective_Start,
          Effective_End: schedule.fields.Effective_End,
          Departure_TimeL: schedule.fields.Departure_TimeL
        }
      })
      return mappedDows
    }
  },
  created () {
    // console.log(this.$route.path)

    if (this.$route && this.$route.params && this.$route.params.o) {
      this.fetchSingleAirport(this.$route.params.o, true)
    }
    if (this.$route && this.$route.params && this.$route.params.d) {
      this.fetchSingleAirport(this.$route.params.d, false)
    }
  },
  methods: {
    daysList (days) {
      const list = days.split(', ').map((day) => {
        const name = day.toLowerCase().slice(0, -1)

        let num
        switch (name) {
          case 'su':
            num = 0
            break

          case 'mo':
            num = 1
            break

          case 'tu':
            num = 2
            break

          case 'we':
            num = 3
            break

          case 'th':
            num = 4
            break

          case 'fr':
            num = 5
            break

          case 'sa':
            num = 6
            break

          default:
            break
        }
        return {
          name,
          num
        }
      })

      return list.sort(function (a, b) {
        return a.num - b.num
      })
    },
    goBack () {
      this.$router.go(-1)
    },
    book (schedule) {
      if (schedule.fields.IsExpedia[0] === 'true') {
        this.startingDate = new Date()
        this.selectedSchedule = schedule.fields
        this.selectedDays = this.daysList(schedule.fields.Frequency_Convert)
      } else {
        window.open(schedule.fields['BookingLink (from Carriers_Alaska)'][0])
      }
    },
    clearSelectedSchedule () {
      console.log('clear')
      this.startingDate = ''
      this.selectedSchedule = {}
    },
    async fetchSingleAirport (iata, isOrig) {
      const airportFetchFilterFormula =
        isOrig
          ? `AND(Is_Origin=1,{IsCurrent-AsOrigin}="Yes",Airport_IATA="${iata}")`
          : `AND(Is_Destination=1,{IsCurrent-AsDest}="Yes",Airport_IATA="${iata}")`

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

      const mapData = await response.json()

      const thisAirport = {
        iata: mapData.records[0].fields.Airport_IATA,
        lat: mapData.records[0].fields.Latitude_Deg,
        long: mapData.records[0].fields.Longitude_Deg,
        icon: mapData.records[0].fields.Icon_Url,
        name: mapData.records[0].fields.Airport_Name,
        municipality: mapData.records[0].fields.Municipality,
        type: mapData.records[0].fields.Type,
        search: mapData.records[0].fields.Search_Field
      }

      switch (isOrig) {
        case true:
          this.selectedOrig = { ...thisAirport }
          break

        case false:
          this.selectedDest = { ...thisAirport }
          break

        default:
          break
      }
    }
  }
}
</script>

<style lang="scss">
.main-with-header {
  margin-top: clamp(20px + 1.75rem, 4rem + 1.75rem, 50px + 1.75rem);
}
</style>
