var RoomData = {
    name: 'RoomData',
    props: ['count'],
    data: function () {
        return {
            defaultAdultCount: 1,
            defaultChildCount: 0,
            defaultChildAgeCount: 0,
            adults: 2,
            childs: [],
            childAges: [],
            modifiedChildCount: 0,
            childageRange: [
                0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18
            ],
            noOfChildsPerRoom: [
                0, 1, 2, 3, 4
            ],
            noOfAdultsPerRoom: [
                1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20
            ],
            childNameLabels: [null, 'st', 'nd', 'rd', 'th'],


        }
    },

    methods: {

        getTotalChilds(e) {
            this.childs = [];
            let numebrOfChilds = Number(e);
            for (let i = 1; i <= numebrOfChilds; i++) {
                this.childs.push(i);
            }

            this.modifiedChildCount = e;

        },

        addChilds(age, childNo) {
            this.childAges[childNo] = age;
        },
    },

    watch: {
        modifiedChildCount: function (newValue, oldValue) {
            if (oldValue > newValue) {
                this.childAges.splice(newValue + 1, Math.abs(newValue - oldValue));
            }
        }
    },


    template: `
            <div>
            <h2 class="dp-label">Room #{{ count }} </h2>
                        <v-row class="my-3">
                            <v-col cols="12" md="6">
                                <label for="adults" class="dp-label">Adults (18+ Years)</label>
                                 <v-select append-icon="fas fa-user-plus" v-model="adults"  outlined :items="noOfAdultsPerRoom"></v-select>
                            </v-col>
                            <v-col cols="12" md="6">
                                <label for="childs" class="dp-label">How Many Children ?</label>
                                 <v-select append-icon="fa fa-child" v-model="defaultChildCount" outlined :items="noOfChildsPerRoom" @change="getTotalChilds($event)"></v-select>
                            </v-col>
                        </v-row>
                        <v-row>
                            <v-col v-for="(child, index) in childs"  cols="12" md="6" :key="index">

                                <label class="dp-label" >{{index +1 }}{{childNameLabels[index+1] }} Child</label>
                                <v-select  :value="defaultChildAgeCount"  outlined :items="childageRange" 
                                @change="addChilds($event, child)"></v-select>                        
                            </v-col>
                        </v-row>
                        </div>
            `

};

Vue.component('villa-search', {
    name: 'VillaSearch',
    props: ['isSessionDefined', 'freeUserInfo'],
    components: {
        'room-data': RoomData,
        'date-calendar': DateCalendar
    },
    data: function () {
        return {
            hasApiMessage: false,
            apiMessage: MESSAGE_IF_RESPONSE_FALSE,
            destinationValue: {
                lat: '',
                lng: '',
                name: '',
                result: '',
              },
              domain: 'us',

              minimumCheckInDate: getVeryNextDate(
                new Date(new Date().setDate(new Date().getDate() + 1))
              ),
              checkInDate: null,
              checkOutDate: null,
            distanceUnit: DISTANCE_UNIT,
            radius: RADIUS,
            loading: false,
            childNameLabels: ['st', 'nd', 'rd', 'th'],
            spickupvalue: '',
            selectedRadius: 15,
            selectedRooms: 1,
            adults: 1,
            childs: 0,
            rooms: [1],
            isDropOffDisabled: true,
            countryDF: DATE_FORMAT,
            DFormat: DATE_FORMAT_PLACEHOLDER,
            isPLoading: false,
            allCitiesJson: [
                'bengaluru',
                'malang',
                'hyderabad',
                'chongqing',
                'ho chi minh city',
                'harbin',
                'ankara',
                'buenos aires',
                'chengdu',
                'ahmedabad',
                'casablanca',
                'chicago',
                "xi'an",
                'madrid',
                'surabaya',
                'pyongyang',
                'nanjing',
                'kinshasa',
                'roma',
                'taipei',
                'osaka',
                'kyiv',
                'yangon',
                'toronto',
                'zibo',
                'dalian',
                'daegu',
                'addis ababa',
                'jinan',
                'salvador',
                'incheon',
                'semarang',
                'giza',
                'changchun',
                'havana',
                'nagoya',
                'belo horizonte',
                'paris',
                'tashkent',
                'fortaleza',
                'sukabumi',
                'cali',
                'guayaquil',
                'qingdao',
                'izmir',
                'cirebon',
                'taiyuan',
                'brasília',
                'bucharest',
                'faisalabad',
                'quezon city',
                'medan',
                'houston',
                'abidjan',
                'mashhad',
                'medellín',
                'kanpur',
                'budapest',
                'caracas',
                'seoul',
                'são paulo',
                'mumbai',
                'jakarta',
                'karachi',
                'moskva moscow',
                'istanbul',
                'mexico city',
                'shanghai',
                'tokyo',
                'new york (ny)',
                'bangkok',
                'beijing',
                'delhi',
                'london',
                'hong kong',
                'cairo',
                'tehran',
                'bogota',
                'bandung',
                'tianjin',
                'lima',
                'rio de janeiro',
                'lahore',
                'bogor',
                'santiago',
                'saint petersburg',
                'shenyang',
                'kolkata',
                'wuhan',
                'sydney',
                'guangzhou',
                'singapore',
                'chennai',
                'baghdad',
                'pusan',
                'los angeles',
                'yokohama',
                'dhaka',
                'berlin',
                'alexandria',
                'rome'
            ],
            NumberOfRooms: [
             1, 2, 3, 4
            ],
            isSessionRemoved: false,
        }
    },

/*
  mounted(){
        if(window.localStorage.getItem('villaSearchedData') !== null){
            this.checkSession();
        }
        this.bindSessionData();
    },
*/
    computed: {
        minimumCheckOutDate() {
            return addDayToDate(this.checkInDate);
          },
      
        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;
            }
          },
        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('villaSearchedData');
                this.isSessionRemoved = true;
            }
        }, 1000);
          },
      
          
          bindSessionData(){
            if(localStorage.getItem('villaSearchedData') !== null){
                let data = JSON.parse(localStorage.getItem('villaSearchedData'));
                this.destinationValue = data.spickup;
                this.checkInDate = data.pick_up_date;
                this.checkInSelected();
                this.selectedRooms = data.selected_rooms;
                this.populateRoom(data.selected_rooms);
                this.selectedRadius = data.selected_radius;
            }
        },
        redirectToRegistartion(){
            if (!this.$refs.villaForm.validate()) {
                let x = this.$el.querySelector('.v-text-field__details');
                this.$vuetify.goTo(x.parentElement.parentElement.parentElement);
                return false;
            }
            else{
                let roomData = [];
                for(let i=0; i<this.rooms.length; i++){
                      roomData.push(this.$refs.rooms[i].$data);
                };

               /*
                let villaSearchedData = {
                    spickup: this.destinationValue,
                    pick_up_location: this.destinationValue.name,
                    pick_up_date: this.checkInDate,
                    selected_rooms: this.selectedRooms,
                    selected_radius: this.selectedRadius,
                    rooms_data: roomData

                };
                window.localStorage.setItem('villaSearchedData',JSON.stringify(villaSearchedData));
                this.checkSession();
                */
               window.location.href = 'Registration.cfm';
            }
      },
      clearForm(){
        this.destinationValue = {
            sPickup: '',
            name: '',
            geoLat: '',
            geoLong: '',
            locationId: '',
            locationType: ' ',
          };
    
          this.checkInDate = null;
          this.checkOutDate = null;
        this.selectedRadius = 15;
        this.rooms = [1];
        this.$refs.rooms[0].defaultChildCount = 0;
        this.$refs.rooms[0].childs = [];
        this.$refs.rooms[0].childAges = [];
        this.$refs.rooms[0].adults=2;
        this.selectedRooms = 1;
  
    },
    populateRoom(e) {
        this.rooms = [];
        let rooms = Number(e);
        for (let i = 1; i <= rooms; i++) {
            this.rooms.push(i);
        }
    },

        submitForm: function () {
            if (!this.$refs.villaForm.validate()) {
                let x = this.$el.querySelector('.v-text-field__details');
                this.$vuetify.goTo(x.parentElement.parentElement.parentElement);
                return false;
            };
        
         let _myDatecheckin = formattedDate(this.checkInDate, this.countryDF);
         let _myDatecheckout = formattedDate(this.checkOutDate, this.countryDF);

            let rooms = [];
            for (let i = 0; i < this.selectedRooms; i++) {
                let roomObj = {
                    adults: this.$refs.rooms[i].adults,
                    childs: this.$refs.rooms[i].childAges.filter(ele => ele !== null)
                }
                rooms.push(roomObj)
            };
    
            let reqPayLoad = {
                radius: this.selectedRadius,
                geoLat: this.destinationValue.lat,
                geoLong: this.destinationValue.lng,
                checkinDate: moment(_myDatecheckin).format('YYYY-MM-DD'), 
                checkoutDate: moment(_myDatecheckout).format('YYYY-MM-DD'),
                desiredResultCurrency: this.CType,
                rooms: rooms,
                search: true,
                residency: RESIDENCY,
                locationData: {
                  ...this.destinationValue.result,
                },
              };
            var searchData = reqPayLoad;
            var searchEngine = {
                "engine": "villas"
            };

           
              var agentData = {
                "username": this.freeUserInfo.getSiteUserName,
                "password": this.freeUserInfo.getSitePassword,
                "domain": DOMAIN
              };

            let self = this;
            var settings = {
                "async": true,
                "crossDomain": true,
                "url": API_URL+SEARCH_REQUESTS_ENDPOINTS['villas'],
                "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']+"villas?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('villaApiMessageContainer');
                      let top = element.getBoundingClientRect().top + window.scrollY;
                      window.scrollTo({
                        top: Math.round(top - 100),
                        behavior: 'smooth'
                      })
            }

            });



        },



    },

    template: `
    <v-card>
    <v-card-text>
    <v-form  class="flight-form" ref="villaForm">
    <v-row id="villaApiMessageContainer">
    <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" md="12">
        <label  class="my-2 dp-label" for="destination">Airport, Landmark, City</label>
            <destination-search
             v-model="destinationValue" 
            :isVilla="true"
             @radiusValue="(e) => (selectedRadius = e)">
             </destination-search>
        </v-col>
    </v-row>



    <v-row>
        <v-col cols="12" md="6" ref="checkinDateMenu">
            <label class="dp-label">Check-In Date</label>
            <date-calendar 
            v-model="checkInDate"
           :minimumDate="minimumCheckInDate"
           @input="
             isDropOffDisabled = true;
             checkInSelected();
           "></date-calendar>
        </v-col>
        <v-col cols="12" md="6" ref="checkoutDateMenu">
            <label class="dp-label">Check-Out Date</label>
            <date-calendar 
            v-model="checkOutDate"
           :minimumDate="minimumCheckOutDate"
          ></date-calendar>
        </v-col>
    </v-row>
    <v-row>
        <v-col cols="12" md="6">
            <label for="NumberOfRooms" class="dp-label">Number of Rooms/Units</label>
            <v-select  append-icon="fas fa-bed" outlined id="NumberOfRooms" :items="NumberOfRooms" 
             v-model="selectedRooms" @change="populateRoom($event)"></v-select>
        </v-col>
        <v-col cols="12" md="6">
            <label for="radius" class="dp-label">Radius ({{ distanceUnit }})</label>
            <v-select append-icon="mdi-map-marker" id="radius" outlined :items="radius" item-text="title" item-value="value"
                v-model="selectedRadius"></v-select>
        </v-col>
    </v-row>
    <room-data ref="rooms" v-for="i in rooms" :key="i" :count="i"></room-data>
    <v-row v-if="isSessionDefined">
        <v-col cols="12" md="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>
</v-card-text>
</v-card>
    `



});