<template>
  <QuickNav selected="Discover"></QuickNav>

  <!-- CONTENT -->
  <section id="Content" class="p-6 pb-24">
    <!-- Heading -->
    <h1 id="ViewHeading" class="text-4xl text-center font-light pt-4 mb-8">
      Discover
    </h1>

    <!-- Quick Search -->
    <div id="QuickSearch" class="mb-4 flex" v-on:keyup.enter="search()">
      <input
        type="text"
        v-model="searchTerms"
        placeholder="Search…"
        class="block w-full rounded-l border border-r-0 border-slate-400 px-3 py-2"
      />
      <button
        @click="search()"
        class="px-4 rounded-r bg-slate-200 border border-l-0 border-slate-400"
      >
        <fa icon="magnifying-glass" class="fa-fw"></fa>
      </button>
    </div>

    <!-- Result Tabs -->
    <div class="text-center text-slate-500 border-b border-slate-300">
      <ul class="flex flex-wrap justify-center gap-4 -mb-px">
        <li>
          <a
            href="#"
            @click="
              projects = [];
              searchLocal();
            "
            v-bind:class="computedLocalTabClassNames()"
          >
            Nearby
            <span
              class="font-semibold text-sm bg-slate-200 px-1.5 py-0.5 rounded-md"
              >{{ localCount }}</span
            >
          </a>
        </li>
        <li>
          <a
            href="#"
            v-bind:class="computedRemoteTabClassNames()"
            @click="
              projects = [];
              search();
            "
          >
            Remote
            <span
              class="font-semibold text-sm bg-slate-200 px-1.5 py-0.5 rounded-md"
              >{{ remoteCount }}</span
            >
          </a>
        </li>
      </ul>
    </div>

    <!-- Loading Animation -->
    <div
      class="fixed left-6 bottom-24 text-center text-4xl leading-none bg-slate-400 text-white w-14 py-2.5 rounded-full"
      v-if="isLoading"
    >
      <fa icon="spinner" class="fa-spin-pulse"></fa>
    </div>

    <!-- Results List -->
    <InfiniteScroll @reached-bottom="loadMoreData">
      <ul>
        <li
          class="border-b border-slate-300"
          v-for="project in projects"
          :key="project.handleId"
        >
          <a
            @click="onClickLoadProject(project.handleId)"
            class="block py-4 flex gap-4"
          >
            <div class="w-12">
              <img
                src="https://picsum.photos/200/200?random=1"
                class="w-full rounded"
              />
            </div>

            <div class="grow">
              <h2 class="text-base font-semibold">Canyon cleanup</h2>
              <div class="text-sm">
                <fa icon="user" class="fa-fw text-slate-400"></fa>
                {{ project.name }}
              </div>
            </div>
          </a>
        </li>
      </ul>
    </InfiniteScroll>
    <AlertMessage
      :alertTitle="alertTitle"
      :alertMessage="alertMessage"
    ></AlertMessage>
  </section>
</template>

<script lang="ts">
import { Component, Vue } from "vue-facing-decorator";

import { accountsDB, db } from "@/db";
import { MASTER_SETTINGS_KEY } from "@/db/tables/settings";
import { accessToken } from "@/libs/crypto";
import AlertMessage from "@/components/AlertMessage";
import QuickNav from "@/components/QuickNav";
import InfiniteScroll from "@/components/InfiniteScroll";

@Component({
  components: { AlertMessage, QuickNav, InfiniteScroll },
})
export default class DiscoverView extends Vue {
  activeDid = "";
  apiServer = "";
  searchTerms = "";
  alertMessage = "";
  alertTitle = "";
  projects: ProjectData[] = [];
  isLocalActive = true;
  isRemoteActive = false;
  localCount = 0;
  remoteCount = 0;
  isLoading = false;

  async mounted() {
    await db.open();
    const settings = await db.settings.get(MASTER_SETTINGS_KEY);
    this.activeDid = settings?.activeDid || "";
    this.apiServer = settings?.apiServer || "";
    this.searchLocal();
  }

  public async buildHeaders() {
    const headers = { "Content-Type": "application/json" };

    if (this.activeDid) {
      await accountsDB.open();
      const allAccounts = await accountsDB.accounts.toArray();
      const account = allAccounts.find((acc) => acc.did === this.activeDid);
      const identity = JSON.parse(account?.identity || "null");

      if (!identity) {
        throw new Error(
          "An ID is chosen but there are no keys for it so it cannot be used to talk with the service.",
        );
      }

      headers["Authorization"] = "Bearer " + (await accessToken(identity));
    } else {
      // it's OK without auth... we just won't get any identifiers
    }
    return headers;
  }

  public async search(beforeId?: string) {
    let queryParams = "claimContents=" + encodeURIComponent(this.searchTerms);

    console.log(beforeId);
    if (beforeId) {
      queryParams = queryParams + `&beforeId=${beforeId}`;
    }

    this.isRemoteActive = true;
    this.isLocalActive = false;

    try {
      this.isLoading = true;
      const response = await fetch(
        this.apiServer + "/api/v2/report/plans?" + queryParams,
        {
          method: "GET",
          headers: await this.buildHeaders(),
        },
      );

      if (response.status !== 200) {
        const details = await response.text();
        throw details;
      }

      const results = await response.json();

      const plans: ProjectData[] = results.data;
      if (plans) {
        for (const plan of plans) {
          const { name, description, handleId = plan.handleId, rowid } = plan;
          console.log("here");
          this.projects.push({ name, description, handleId, rowid });
        }
        this.remoteCount = this.projects.length;
      } else {
        throw JSON.stringify(results);
      }
    } catch (e) {
      console.log("Error with feed load:", e);
      this.alertMessage =
        e.userMessage || "There was an error retrieving projects.";
      this.alertTitle = "Error";
    } finally {
      this.isLoading = false;
    }
  }

  public async searchLocal(beforeId?: string) {
    const claimContents =
      "claimContents=" + encodeURIComponent(this.searchTerms);
    let queryParams = [
      claimContents,
      "minLocLat=40.901000",
      "maxLocLat=40.904000",
      "westLocLon=-111.914000",
      "eastLocLon=-111.909000",
    ].join("&");

    if (beforeId) {
      queryParams = queryParams + `&beforeId=${beforeId}`;
    }

    try {
      this.isLoading = true;
      this.isLocalActive = true;
      this.isRemoteActive = false;
      const response = await fetch(
        this.apiServer + "/api/v2/report/plansByLocation?" + queryParams,
        {
          method: "GET",
          headers: await this.buildHeaders(),
        },
      );

      if (response.status !== 200) {
        throw await response.text();
      }

      const results = await response.json();

      if (results.data) {
        if (beforeId) {
          const plans: ProjectData[] = results.data;
          for (const plan of plans) {
            const { name, description, handleId = plan.handleId, rowid } = plan;
            if (beforeId !== plan["rowid"]) {
              this.projects.push({ name, description, handleId, rowid });
            }
          }
        } else {
          this.projects = results.data;
        }
        this.localCount = this.projects.length;
      } else {
        throw JSON.stringify(results);
      }
    } catch (e) {
      console.log("Error with feed load:", e);
      this.alertMessage =
        e.userMessage || "There was an error retrieving projects.";
      this.alertTitle = "Error";
    } finally {
      this.isLoading = false;
    }
  }

  /**
   * Data loader used by infinite scroller
   * @param payload is the flag from the InfiniteScroll indicating if it should load
   **/
  async loadMoreData(payload: boolean) {
    if (this.projects.length > 0 && payload) {
      const latestProject = this.projects[this.projects.length - 1];
      console.log("rowid", latestProject, payload);
      console.log(Object.keys(latestProject));
      if (this.isLocalActive) {
        this.searchLocal(latestProject["rowid"]);
      } else if (this.isRemoteActive) {
        this.search(latestProject["rowid"]);
      }
    }
  }

  /**
   * Handle clicking on a project entry found in the list
   * @param id of the project
   **/
  onClickLoadProject(id: string) {
    localStorage.setItem("projectId", id);
    const route = {
      name: "project",
    };
    this.$router.push(route);
  }

  public computedLocalTabClassNames() {
    return {
      "inline-block": true,
      "py-3": true,
      "rounded-t-lg": true,
      "border-b-2": true,
      active: this.isLocalActive,
      "text-blue-600": this.isLocalActive,
      "border-blue-600": this.isLocalActive,
      "font-semibold": this.isLocalActive,
      "border-transparent": !this.isLocalActive,
      "hover:text-slate-600": !this.isLocalActive,
      "hover:border-slate-300": !this.isLocalActive,
    };
  }

  public computedRemoteTabClassNames() {
    return {
      "inline-block": true,
      "py-3": true,
      "rounded-t-lg": true,
      "border-b-2": true,
      active: this.isRemoteActive,
      "text-blue-600": this.isRemoteActive,
      "border-blue-600": this.isRemoteActive,
      "font-semibold": this.isRemoteActive,
      "border-transparent": !this.isRemoteActive,
      "hover:text-slate-600": !this.isRemoteActive,
      "hover:border-slate-300": !this.isRemoteActive,
    };
  }
}
</script>
