import useTranslate from "../../../hooks/useTranslate.js";
import { CaptionComponent } from "./component/CaptionComponent.js";
import { RadioComponent } from "./component/RadioComponent.js";
import { SearchComponent } from "./component/SearchComponent.js";
import { TableComponent } from "./component/TableComponent.js";
import useSearch from "./hooks/useSearch.js";
import useKOSearchBlockStore from "./store/index.js";


const { ref, onMounted } = Vue;

export const App = {
  components: {
    'caption-component': CaptionComponent,
    'search-component':  SearchComponent,
    'radio-component':   RadioComponent,
    'table-component':   TableComponent,
  },

  setup() {
    const store = useKOSearchBlockStore();
    const preloader = ref(false);
    const data = ref([]);
    const last_lines = ref([]);

    async function search(need_last_lines) {
      preloader.value = true;

      let result = await useSearch(need_last_lines);
      if (need_last_lines) {
        last_lines.value = result;
      } else {
        if (last_lines.value.length > 0) {
          last_lines.value = [];
        }
        data.value = result;
      }

      preloader.value = false;
    }

    onMounted(async () => await search(true));

    return {
      store,
      preloader,
      last_lines,
      data,
      getTranslate: useTranslate,
      handle: _.debounce(() => {
        search(store.search_string);
        setTimeout(() => $('.repconview__table_table').fixedTable(), 500);
      }, 500),
    }
  },

  template: /*html*/`
    <div>
      <caption-component />

      <div class="repconview__table_table" style="padding-top: 0;">
        <search-component @handle-change='handle' />
        <radio-component @handle-change='handle' />

        <div
          v-if='preloader'
          style="text-align: center; margin-top: 20px;"
        >{{ getTranslate('Sync_pas_m') }}...</div>

        <div
          v-else-if='last_lines.length > 0'
          class="repconview__table_inner"
          style="overflow: auto hidden;"
        >
          <table-component :rows='last_lines'></table-component>

          <div
            class="repconview__table-legend"
            style="overflow: hidden;"
          >
            {{ getTranslate('Total_lines') + ' ' + last_lines.length }}
          </div>
        </div>

        <div
          v-else
          class="repconview__table_inner"
          style="overflow: auto hidden;"
        >
          <table-component :rows='data'></table-component>

          <div
            v-if='store.search_string != ""'
            class="repconview__table-legend"
            style="overflow: hidden;"
          >
            {{ getTranslate('Lines_found') + ' ' + data.length }}
          </div>
        </div>
      </div>
    </div>
  `
}
