Vue.component('round-trip',{
    name: 'RoundTrip',
    components:{
      'date-calendar': DateCalendar
    },
    props:['isSessionDefined', 'freeUserInfo', 'booktravelPage'],
    data:()=> ({
      hasApiMessage: false,
      apiMessage: MESSAGE_IF_RESPONSE_FALSE,
      departure: {
          name: '',
          result: '',
        },
        arrival: {
          name: '',
          result: '',
        },
  
        departDate:null,
        arrivalDate: null,
  
        items: [0, 1, 2, 3, 4, 5, 6],
        adults: 2,
        seniors: 0,
        infants: 0,
        childs: 0,
        cabinClasses: [
            { title: 'Economy', value: 'Economy' },
            { title: 'Premium Economy', value: 'PremiumEconomy' },
            { title: 'Business', value: 'Business' },
            { title: 'First', value: 'First' }
            ],
        cabinClass: 'Economy',
        connections: [
    { title: 'Direct', value: 'Direct' },
    { title: 'One Connection', value: 'OneConn' },
    { title: 'All', value: 'All' }
   ],
        connection: 'All',
        loading: false,
        nearbyDest: false,
        nearbySource: false,
  
    }),
  
/*    mounted(){
      if(window.localStorage.getItem('roundTripFlightSearchedData') !== null){
          this.checkSession();
      }
      this.bindSessionData();
  },
  */
    watch:{
        departure:{
            deep: true,
            handler(obj){
                this.nearbySource = obj.result.type === 'City'
            }
        },
        arrival:{
            deep: true,
            handler(obj){
            this.nearbyDest = obj.result.type === 'City'
            }
    }
    
    },
    methods: {
      submitForm() {
          let valid = this.$refs['roundTripForm'].validate();
          if (!valid) {
              let x = this.$el.querySelector('.v-text-field__details');
              this.$vuetify.goTo(x.parentElement.parentElement.parentElement);
              return false;
          }
          
          var agentData = {   
              "username": this.freeUserInfo.getSiteUserName,  
              "password": this.freeUserInfo.getSitePassword,  
              "domain": DOMAIN
          };

          let reqPayLoad = {
              search: true,
              source: [this.departure.result.iata],
              sourceType: [this.departure.result.type],
              dest: [this.arrival.result.iata],
              destType: [this.arrival.result.type],
              date: [this.departDate, this.arrivalDate],
              airportArriveRound: [this.arrival.result.name],
              airportDepartRound: [this.departure.result.name],
              adults: this.adults,
              cabinClass: this.cabinClass,
              connections: this.connection,
              flightType: 'roundTrip',
              nearbySource: [this.nearbySource],
              nearbyDest: [this.nearbyDest],
              seniors: this.seniors,
              child: this.childs,
              infants: this.infants,
              sortBy: 'asc',
              searchId: null,
            };
          var searchData = reqPayLoad;
          var searchEngine = {
              "engine": "flights"
          };
  
          let self = this;
          var settings = {
              "async": true,
              "crossDomain": true,
              "url": API_URL+SEARCH_REQUESTS_ENDPOINTS['flights'],
              "type": "POST",
              "headers": {
                  "Accept": "application/json",
                  "Content-Type": "application/json",
              },
              "data": JSON.stringify({
                  "data": [{
                      "agentData": agentData,
                      "searchData": searchData,
                      "searchEngine": searchEngine,
                      "searchId": ""
                  }]
              }),
              beforeSend: function () {
                  self.loading = true;
              },
          };
  
  
          $.ajax(settings).done(function (response) {
              if (response.success) {
                  self.loading = false;
                  const redirecturl = REDIRECT_URL['com']+"flights?searchId=" +
                      response.data
                      .searchId + "&token=" + response.data.token;
                  window.location.href = redirecturl;
                  return false;
              } else if(!response.success){ 
                  self.loading = false;
                    self.hasApiMessage = true;
                    let element = document.getElementById('roundTripApiMessageContainer');
                    let top = element.getBoundingClientRect().top + window.scrollY;
                    window.scrollTo({
                      top: Math.round(top - 100),
                      behavior: 'smooth'
                    });
                  
          }
          });
  
  
  
      },
      clearForm() {
          this.departure = {
            name: '',
            result: '',
          };
          this.arrival = {
            name: '',
            result: '',
          };
          this.departDate = '';
          this.arrivalDate = '';
          this.seniors = 0;
          this.adults =2;
          this.childs =0;
          this.infants = 0;
          this.connection = 'All';
          this.cabinClass = 'Economy';
        },
      checkInSelected() {
          let nextDayValue = nextDay(this.departDate, this.arrivalDate);
          if (nextDayValue) {
            this.arrivalDate = nextDayValue;
          }
        },
        checkSession(){
          var time = 1200; 
          var saved_countdown = localStorage.getItem('saved_countdown');
          
          if(saved_countdown == null) {
              var new_countdown = new Date().getTime() + (time) * 1000;
              time = new_countdown;
              localStorage.setItem('saved_countdown', new_countdown);
          } else {
              time = saved_countdown;
          }
           
         var x = setInterval(() => {
        
          var now = new Date().getTime();
      
          var distance = time - now;
  
          var counter = Math.floor((distance % (1000 * 60 * 60)) / 1000);
      
          if (counter <= 0) {
              clearInterval(x);
              localStorage.removeItem('saved_countdown');
              localStorage.removeItem('roundTripFlightSearchedData');
              this.isSessionRemoved = true;
          }
      }, 1000);
        },
        bindSessionData(){
          if(localStorage.getItem('roundTripFlightSearchedData') !== null){
              let data = JSON.parse(localStorage.getItem('roundTripFlightSearchedData'));
              this.departure = data.depart_pick;
              this.arrival = data.arrival_pick;
              this.departDate = data.departure_date;
              this.checkInSelected();
              this.adults = data.adults;
              this.cabinClass = data.cabinClass;
              this.childs = data.childs;
              this.infants = data.infants;
              this.nearbySource = data.near_by_source;
              this.nearbyDest = data.near_by_destionation;
              this.connection = data.connection;
              this.seniors = data.seniors;
          }
      },
        redirectToRegistartion(){
          if (!this.$refs.roundTripForm.validate()) {
            let x = this.$refs.roundTripForm.$el.querySelector('.v-text-field__details');
            this.$vuetify.goTo(x.parentElement.parentElement.parentElement); 
            return false;
          }
          else{
            /*
            let roundTripFlightSearchedData = {
                      depart_pick: this.departure,
                      arrival_pick: this.arrival,
                      depature_location: this.departure.name,
                      arrival_location: this.arrival.name,
                      departure_date: this.departDate,
                      arrival_date: this.arrivalDate,
                      near_by_source: this.nearbySource,
                      near_by_destionation: this.nearbyDest,
                      adults: this.adults,
                      seniors: this.seniors,
                      childs: this.childs,
                      infants: this.infants,
                      cabinClass: this.cabinClass,
                      connection: this.connection,
                  };
                  window.localStorage.setItem('roundTripFlightSearchedData',JSON.stringify(roundTripFlightSearchedData));
                  this.checkSession();
                  */
                  window.location.href = "Registration.cfm";
                
          }
        },
    },
  
    computed:{
      minDepartureDate(){
          return getVeryNextDate(
               new Date(new Date().setDate(new Date().getDate() + 1))
             );
       },
       minDropOff() {
     return moment(this.departDate, 'YYYY-MM-DD')
       .add('days', 1)
       .format('YYYY-MM-DD');
    }
    },
  
    template:
    `
       <div>
            <v-form class="flight-form" ref="roundTripForm">
            <v-row id="roundTripApiMessageContainer">
            <v-col cols="12" md="12">
            <v-alert
            v-if="hasApiMessage"
            dense
            outlined
            type="error"
          >
        
          <span v-html="apiMessage"></span>
          
          </v-alert>
            </v-col>
            </v-row>
                <v-row>
                    <v-col cols="12" sm="6">
                        <label class="dp-label">Departure
                            airport</label>
                          <flight-location v-model="departure"></flight-location>
                        <v-checkbox v-model="nearbySource"
                            class="include-airport">
                            <template v-slot:label
                                for="inc-nb-dep">&nbsp;
                                Include nearby
                                airports</template>
                        </v-checkbox>
                    </v-col>
                    <v-col cols="12" sm="6"
                        ref="roundTripDepartDateContainer">
                        <label class="dp-label"
                            for="departing-on"
                            aria-labelledby="departing-on">Departing
                            on</label>
                        <template>
                        <date-calendar 
                        v-model="departDate"
                        :minimum-date="minDepartureDate"
                        @input="checkInSelected()">
                      </date-calendar>
                        </template>
                        <small>Flight cannot be booked more
                            than 11 months in
                            advance.</small>
                    </v-col>
                </v-row>
               
  
  
                <v-row style="margin-top: 0;">
                    <v-col cols="12" sm="6">
                        <label class="dp-label">Arrival
                            airport</label>
                          <flight-location v-model="arrival"></flight-location>
  
                        <v-checkbox v-model="nearbyDest"
                            class="include-airport">
                            <template v-slot:label>&nbsp;
                                Include nearby
                                airports</template>
  
                        </v-checkbox>
  
                    </v-col>
                    <v-col cols="12" sm="6"
                        ref="roundTripReturnDateContainer">
                        <label class="dp-label">Returning
                            on</label>
                        <template>
                        <date-calendar  v-model="arrivalDate" :minimum-date="minDropOff"></date-calendar>
                        </template>
                        <small>Flight cannot be booked more
                            than 11 months in
                            advance.</small>
                    </v-col>
                </v-row>
                <v-row style="margin-top: 0;">
                    <v-col cols="12" sm="6">
                        <label class="dp-label">Adults (12 yrs - 65 yrs)</label>
                        <v-select v-model="adults"
                            :items="items" outlined>
                        </v-select>
                    </v-col>
                    <v-col cols="12" sm="6">
                        <label class="dp-label">Seniors (65+ yrs)</label>
                        <v-select v-model="seniors"
                            :items="items" outlined>
                        </v-select>
                    </v-col>
                </v-row>
                <v-row>
                    <v-col cols="12" sm="6">
                        <label class="dp-label">Children (Below 12 yrs)</label> <v-select
                                v-model="childs" :items="items"
                                outlined>
                                </v-select>
                    </v-col>
                    <v-col cols="12" sm="6">
                        <label class="dp-label">Lap Infants (Below 2 yrs)</label> <v-select
                                v-model="infants" :items="items"
                                outlined>
                                </v-select>
                    </v-col>
                </v-row>
                <v-row>
                    <v-col cols="12" sm="6">
                        <label class="dp-label">Cabin
                            Class</label>
                        <v-select v-model="cabinClass"
                            :items="cabinClasses" item-text="title" item-value="value" outlined>
                        </v-select>
                    </v-col>
                    <v-col cols="12" sm="6">
                        <label class="dp-label">Max
                            Connections</label>
                        <v-select v-model="connection"
                            :items="connections" item-text="title" item-value="value" outlined>
                        </v-select>
                    </v-col>
                </v-row>
                <v-row>
                    <v-col cols="6" sm="6" v-if="booktravelPage">
                        <a href="https://inteletravel.com/booktravel-flights.cfm"
                            style="text-decoration: none;">Click
                            here for one-way multi-leg
                            flight search options.</a>
                    </v-col>
                </v-row>
                <v-row v-if="isSessionDefined">
                    <v-col cols="6" sm="6">
                        <v-btn large type="button" :loading="loading" class="custom-red"
                            @click="submitForm">
  
                            Search
                        </v-btn>
                        <v-btn large type="button" style="font-weight: 600px; font-size: 14px; box-shadow: none; background: transparent; color: #949494; text-transform: uppercase;"
                            @click="clearForm()">Reset
                        </v-btn>
                    </v-col>
                </v-row>    
                    <v-row v-if="!isSessionDefined">
                    <v-col cols="12" md="6">
                    <v-btn large 
                    type="button"
                    class="custom-red"
                    @click="redirectToRegistartion"
                   >
                    Search and Register Now
                   </v-btn>
                    </v-col>
                    </v-row>
            </v-form>
            </div>
  `
  });