<template>
  <ion-page>
    <ion-header>
      <ion-toolbar>
        <ion-buttons slot="start">
          <ion-back-button></ion-back-button>
        </ion-buttons>
        <ion-title>
          Search
        </ion-title>
      </ion-toolbar>
    </ion-header>
    <ion-content class='ion-padding'>
      <ion-searchbar :debounce="1000" @ionInput="handleInput($event)"></ion-searchbar>
      <ion-list>
        <template v-for="result in results">
          <SearchItem :obj="result" />
        </template>
        <template v-if="processing">
            <ion-progress-bar type="indeterminate"></ion-progress-bar>

        </template>
        <template v-if="is_empty">
          <h1 class='ion-text-center'>Search not found</h1>
        </template>
      </ion-list>
      <ion-infinite-scroll @ionInfinite="loadMore">
        <ion-infinite-scroll-content></ion-infinite-scroll-content>
      </ion-infinite-scroll>
    </ion-content>
  </ion-page>
</template>

<script setup lang="ts">
import { IonPage, IonHeader, IonToolbar, IonTitle, IonContent, IonButton, onIonViewWillEnter, IonList, IonSearchbar, IonLabel,
IonItem, IonBackButton, IonProgressBar, IonButtons, IonInfiniteScroll,
    IonInfiniteScrollContent, InfiniteScrollCustomEvent } from '@ionic/vue';
import ExploreContainer from '@/components/ExploreContainer.vue';
import { defineComponent, onMounted } from 'vue';
import { GoogleAuth } from '@codetrix-studio/capacitor-google-auth';
import { searchMat, callUrl } from '@/composable/settings';

import { ref } from 'vue';
import SearchItem from '@/components/SearchItem.vue';

const results = ref();
const is_empty = ref(false);
const processing = ref(false)
let next_url = null
const handleInput = async (event) => {
  console.log("handleInput")
  console.log(event)
  const query = event.target.value.toLowerCase();
  console.log("query = ", query)
  is_empty.value = false;
  if(query == "") {
    results.value = []
  }else {
    results.value = []
    //results.value = data.filter((d) => d.toLowerCase().indexOf(query) > -1);
    processing.value = true;
    const r = await searchMat(query)
    processing.value = false;

    results.value = r.results
    next_url  = r.next
    if(r.count == 0 ) {
      is_empty.value = true;
    }else {
      is_empty.value = false;
    }
  }
  //test
}
  const loadMore = async (ev: InfiniteScrollCustomEvent) => {
    //setTimeout(() => ev.target.complete(), 500);
    console.log("next url ", next_url)
    if(next_url) {
      let data  = await callUrl(next_url)
      console.log("data results", data.results)
      results.value.push(data.results)
      next_url = data.next
      ev.target.complete()
    }else {
      ev.target.complete()
    }
  };
</script>
