Vue.component("car-search", {
  name: "CarSearch",
  components:{
    'date-calendar': DateCalendar
  },
  props: ['isSessionDefined', 'freeUserInfo'],
  data: function () {
    return {
      hasApiMessage: false,
      apiMessage: MESSAGE_IF_RESPONSE_FALSE,
      checkInDate: null,
      minimumCheckInDate: getVeryNextDate(
        new Date(new Date().setDate(new Date().getDate()))
      ),
      checkOutDate: null,
      pickUpLocation: {
        name: '',
        result: '',
      },
      dropOffLocation: {
        name: '',
        result: '',
      },
      isSessionRemoved: false,
      DFormat: DATE_FORMAT_PLACEHOLDER,
      isPLoading: false,
      sdriverAge: "",
      inDriverAge: "30",
      isDropOffDisabled: true,
      pickingTimes: [],
      dftPickingTimes: "12:00:00",
      dftDropingTimes: "12:00:00",
      driverAgeRules: [
        (v) => !!v || "Driver Age is required",
        (v) => (v && v >= 17) || "The driver age must be at least 17.",
        (v) => (v && v <= 99) || "The driver age may not be greater than 99.",
      ],
      mainLocation: 'Airport',
      mainLocationRules: [
        (v) => !!v || 'At least one location should be selected',
      ],
      checked: true,
      loading:false,

      countryDF: DATE_FORMAT,
      pickingTimes: [
        { title: 'Midnight', value: '00:00:00' },
        { title: '1:00 AM', value: '01:00:00' },
        { title: '2:00 AM', value: '02:00:00' },
        { title: '3:00 AM', value: '03:00:00' },
        { title: '4:00 AM', value: '04:00:00' },
        { title: '5:00 AM', value: '05:00:00' },
        { title: '6:00 AM', value: '06:00:00' },
        { title: '7:00 AM', value: '07:00:00' },
        { title: '8:00 AM', value: '08:00:00' },
        { title: '9:00 AM', value: '09:00:00' },
        { title: '10:00 AM', value: '10:00:00' },
        { title: '11:00 AM', value: '11:00:00' },
        { title: 'Noon', value: '12:00:00' },
        { title: '1:00 PM', value: '13:00:00' },
        { title: '2:00 PM', value: '14:00:00' },
        { title: '3:00 PM', value: '15:00:00' },
        { title: '4:00 PM', value: '16:00:00' },
        { title: '5:00 PM', value: '17:00:00' },
        { title: '6:00 PM', value: '18:00:00' },
        { title: '7:00 PM', value: '19:00:00' },
        { title: '8:00 PM', value: '20:00:00' },
        { title: '9:00 PM', value: '21:00:00' },
        { title: '10:00 PM', value: '22:00:00' },
        { title: '11:00 PM', value: '23:00:00' }
      ],

    };
  },
/*
 mounted: function () {
    if(window.localStorage.getItem('carSearchedData') !== null){
        this.checkSession();
    }
    this.bindSessionData();
    
  }, 
*/
  computed: {
    minimumCheckOutDate() {
      return addDayToDate(this.checkInDate);
    },

    compPickDateFormatted: {
      get: function () {
        return formattedDate(this.checkInDate, this.countryDF);
      },
      set: function (newValue) {
        this.checkInDate = formattedDate(newValue, this.countryDF);
      },
    },
    compDropDateFormatted: {
      get: function () {
        return formattedDate(this.checkOutDate, this.countryDF);
      },
      set: function (newValue) {
        this.checkOutDate = formattedDate(newValue, this.countryDF);
      },
    },
    minDropOff() {
      return moment(this.date1, "YYYY-MM-DD")
        .add("days", 1)
        .format("YYYY-MM-DD");
    },

  },
  methods: {
    checkInSelected() {
      let nextDayValue = nextDay(this.checkInDate, this.checkOutDate);
      if (nextDayValue) {
        this.checkOutDate = nextDayValue;
      }
    },
    pickUpSelected(result) {
      this.pickUpLocation = { ...result };
      this.dropOffLocation = { ...this.pickUpLocation };
    },
    checkSession(){
      var time = 1200; // This is the time allowed
      var saved_countdown = localStorage.getItem('saved_countdown');
      
      if(saved_countdown == null) {
          // Set the time we're counting down to using the time allowed
          var new_countdown = new Date().getTime() + (time) * 1000;
      
          time = new_countdown;
          localStorage.setItem('saved_countdown', new_countdown);
      } else {
          time = saved_countdown;
      }
       
    // Update the count down every 1 second
    var x = setInterval(() => {
    
      // Get today's date and time
      var now = new Date().getTime();
  
      // Find the distance between now and the allowed time
      var distance = time - now;
  
      // Time counter
      var counter = Math.floor((distance % (1000 * 60 * 60)) / 1000);
  
      // Output the result in an element with id="demo"
      // If the count down is over, write some text 
      if (counter <= 0) {
          clearInterval(x);
          localStorage.removeItem('saved_countdown');
          localStorage.removeItem('carSearchedData');
          this.isSessionRemoved = true;
      }
  }, 1000);
    },

    
    bindSessionData(){
      if(localStorage.getItem('carSearchedData') !== null){
          let data = JSON.parse(localStorage.getItem('carSearchedData'));
          this.mainLocation = data.main_location;
          this.minimumCheckInDate = data.min_date;
          this.checkInDate = data.pick_up_date;
          this.checkInSelected();
          this.dftPickingTimes = data.pick_up_time;
          this.dftDropingTimes = data.drop_of_time;
          this.pickUpLocation = data.pickup;
          this.inDriverAge = data.driver_age;
          this.pickUpSelected(data.pickup);
      }
  },
    redirectToRegistartion(){
      if (!this.$refs.carForm.validate()) {
        let x = this.$el.querySelector('.v-text-field__details');
        this.$vuetify.goTo(x.parentElement.parentElement.parentElement);
        return false;
      }
      else{
        /*  let carSearchedData = {
              pickup: this.pickUpLocation,
              main_location: this.mainLocation,
              min_date: this.minimumCheckInDate,
              pick_up_date: this.checkInDate,
              pick_up_time: this.dftPickingTimes,
              drop_of_time: this.dftDropingTimes,
              driver_age: this.inDriverAge

          };

          window.localStorage.setItem('carSearchedData',JSON.stringify(carSearchedData));
          this.checkSession();
          */
          window.location.href = 'Registration.cfm';
      }
    },
    clearForm() {
      this.checkInDate = null;
      this.checkOutDate = null;

      this.inDriverAge = '30';
      this.dftPickingTimes = '12:00:00';
      this.dftDropingTimes = '12:00:00';
      this.pickUpLocation = {
        name: '',
        result: '',
      };
      this.dropOffLocation = {
        name: '',
        result: '',
      };

    },




    submitForm: function () {
      if (!this.$refs.carForm.validate()) {
        let x = this.$el.querySelector('.v-text-field__details');
        this.$vuetify.goTo(x.parentElement.parentElement.parentElement);
        return false;
      };
      let that = this;
      let _pickTime = that.compPickDateFormatted + " " + that.dftPickingTimes;
      let _dropTime = that.compDropDateFormatted + " " + that.dftDropingTimes;

      _pickTime = moment(
        _pickTime,
        this.DFormat + " hh:mm A"
      ).unix();
      _dropTime = moment(
        _dropTime,
        this.DFormat + " hh:mm A"
      ).unix();
    

      let pickPayload = {
        date: moment(_pickTime, "X").format("YYYY-MM-DDTHH:mm:ss"),
        locationKey: that.pickUpLocation.result.VALUE,
        locationName: that.pickUpLocation.result.LABEL,
        time: moment(_pickTime, "X").format("HH:mm:ss"),
      };
      let dropPayload = {
        date: moment(_dropTime, "X").format("YYYY-MM-DDTHH:mm:ss"),
        locationKey: that.dropOffLocation.result.VALUE,
        locationName: that.dropOffLocation.result.LABEL,
        time: moment(_dropTime, "X").format("HH:mm:ss"),
      };
      let reqPayLoad = {
        desiredResultCurrency: DESIRED_CURRENCY,
        pickUp: pickPayload,
        dropOff: dropPayload,
        driversAge: that.inDriverAge,
        residency: RESIDENCY
      };
      
      var agentData = {
        "username": this.freeUserInfo.getSiteUserName,
        "password": this.freeUserInfo.getSitePassword,
        "domain": DOMAIN
      };

      var searchData = reqPayLoad;
      var searchEngine = {
        "engine": "cars"
      };

      let self = this;
      var settings = {
        "async": true,
        "crossDomain": true,
        "url": API_URL+SEARCH_REQUESTS_ENDPOINTS['cars'],
        "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+"cars?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('carApiMessageContainer');
            let top = element.getBoundingClientRect().top + window.scrollY;
            window.scrollTo({
              top: Math.round(top - 100),
              behavior: 'smooth'
            });
  }
      });
    },
  },
  watch: {
    mainLocation() {
        this.pickUpLocation = {
          name: '',
          result: '',
        };
        this.dropOffLocation = {
          name: '',
          result: '',
        };

    },
  },

  template: `
  <v-card>
  <v-card-text>
  <v-form ref="carForm" class="flight-form" lazy-validation>
  <v-row id="carApiMessageContainer">
  <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>
  <div>
    <v-radio-group
      v-model="mainLocation"
      required
      :rules="mainLocationRules"
      column
    >
      <ul style="list-style: none; display: flex;">
        <li class="mr-3">
          <v-radio
          class="dp-label"
            label="Airport Locations"
            color="primary"
            value="Airport"
            name="search_main_location"
            :checked="checked"
          ></v-radio>
        </li>
        <li>
          <v-radio
          class="dp-label"
            label="City Locations"
            color="primary"
            value="City"
            name="search_main_location"
          ></v-radio>
        </li>
      </ul>
    </v-radio-group>
  </div>
    <v-row>
      <v-col cols="12" md="6" sm="12">
      <label class="dp-label" >Pick-up Location</label>
      <car-location 
      :value="pickUpLocation"
      @input="pickUpSelected"
      :mainLocation="mainLocation">
      </car-location>
       </div>
       </v-col>
       <v-col cols="12" md="6" sm="12">
    <label class="dp-label">Drop-off Location</label>

      <car-location 
      :value="dropOffLocation"
      :mainLocation="mainLocation">
      </car-location> 

    </v-col>  
        </v-row>

        <v-row>
        <v-col cols="12" md="3" sm="12" ref="pickupDate">
        <label  class="dp-label">Pick-up Date</label>
        <date-calendar 
         v-model="checkInDate"
        :minimumDate="minimumCheckInDate"
        @input="
          isDropOffDisabled = true;
          checkInSelected();
        "></date-calendar>
       
        </v-col>
        <v-col cols="12" md="3" sm="12">
        <label class="dp-label">Pick-up Time</label>

        <v-select
        outlined
        class="date pickingTimes"
        :items="pickingTimes"
        item-text="title"
        item-value="value"
        v-model="dftPickingTimes"
      >
      </v-select>
        </v-col>
     
    <v-col cols="12" md="3" sm="12" ref="dropOffDate">
    <label class="dp-label">Drop-off Date</label>
    <date-calendar
    v-model="checkOutDate"
    :minimumDate="minimumCheckOutDate"
  ></date-calendar>
    <!--<v-menu
    :attach="$refs.dropOffDate"
    content-class="date-picker-backoffice"
    v-model="menu2"
    :open-on-focus="true"
    :close-on-content-click="false"
    transition="scale-transition"
    offset-y
    max-width="290"
    min-width="auto"
  >
    <template
      v-slot:activator="{
        on,
        attrs
      }"
    >
        <v-text-field
          outlined
          v-model="compDropDateFormatted"
          :placeholder="countryDF"
          append-icon="mdi-calendar"
          readonly
          v-bind="attrs"
          v-on="on"
          :disabled="!isDropOffDisabled"
          :rules="[dropDateRules, checkDate]"
          @mousedown.prevent="openDropOffDate"
        ></v-text-field>
    </template>
    <v-date-picker
      v-model="date2"
      @input="menu2 = false"
      :min="minDropOff"
      no-title
    ></v-date-picker>
  </v-menu>-->
    </v-col>

    <v-col cols="12" md="3" sm="12">
    <label class="dp-label">Drop-off Time</label>
    <v-select
    outlined
    class="date pickingTimes"
    :items="pickingTimes"
    item-text="title"
    item-value="value"
    v-model="dftDropingTimes"
  ></v-select>
    </v-col>
    </v-row>
   
    <v-row>
    <v-col cols="12" md="6">
    <label class="dp-label">Driver’s age</label>
    <v-text-field
    outlined
    placeholder="Enter Driver’s age"
    append-icon="fas fa-user-secret"
    v-model="inDriverAge"
    :rules="driverAgeRules"
  >
  </v-text-field>
    </v-col>
    </v-row>
    
    <v-row v-if="isSessionDefined">
    <v-col cols="12" md="6">
    <v-btn
    large  
    :loading="loading"
    type="button"
    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>
</v-card-text>
</v-card>
  `,
});