<template>
  <div class="dashboard-page">
    <!-- <div class="container"> -->
    <!-- <div class="row"> -->
    <!-- <div class="col-12"> -->
    <div class="row row-gap">
      <div v-if="canView">
        <div v-if="systems.length">
          <div v-if="layout == 'card'">
            <div v-for="project in systems" :key="project.id" class="col-lg-3">
              <a
                :href="project.link"
                @click.prevent="redirectTo(project)"
                :disabled="project?.loading"
                class="card system-card no-text-decoration"
                :title="project.title"
              >
                <div class="card-img-top">
                  <NuxtImg :src="projectIcon(project.link)" :alt="project.title" />
                </div>

                <div class="card-body">
                  <h5 class="card-title">
                    {{ project.title }}
                    <!--                    <small>-->
                    <!--                      ({{ organ }})-->
                    <!--                    </small>-->
                  </h5>
                  <p class="card-text">
                    {{ project.comment }}
                  </p>
                </div>

                <the-button-loading
                  v-if="project?.loading"
                ></the-button-loading>
              </a>
            </div>
          </div>

          <div v-else-if="layout == 'horizontal'">
            <div v-for="project in systems" :key="project.id" class="col-12">
              <a
                :href="project.link"
                @click.prevent="redirectTo(project)"
                :disabled="project?.loading"
                class="card system-card no-text-decoration"
                :class="layout"
                :title="project.title"
              >
                <div class="card-img-top">
                  <img
                    class="img-fluid"
                    :src="projectIcon(project.link)"
                    :alt="project.title"
                  />
                </div>

                <div class="card-body">
                  <h5 class="card-title">
                    {{ project.title }}
                    <!--                    <small>-->
                    <!--                      ({{ organ }})-->
                    <!--                    </small>-->
                  </h5>
                  <p class="card-text">
                    <!-- {{ project.link + "Description" }} -->
                    {{ project.comment }}
                  </p>
                </div>

                <the-button-loading
                  v-if="project?.loading"
                ></the-button-loading>
              </a>
            </div>
          </div>

          <div v-else-if="layout == 'list'">
            <div v-for="project in systems" :key="project.id" class="col-12">
              <a
                :href="project.link"
                @click.prevent="redirectTo(project)"
                :disabled="project?.loading"
                class="card system-card no-text-decoration"
                :class="layout"
                :title="project.title"
              >
                <div class="card-img-top">
                  <img
                    class="img-fluid"
                    :src="projectIcon(project.link)"
                    :alt="project.title"
                  />
                </div>

                <div class="card-body">
                  <h5 class="card-title">
                    {{ project.title }}
                  </h5>
                </div>

                <the-button-loading
                  v-if="project?.loading"
                ></the-button-loading>
              </a>
            </div>
          </div>
        </div>
        <no-data class="col-12" v-else></no-data>
      </div>
      <no-data v-else>
        <the-content-loading v-if="fetchingData"></the-content-loading>

        <div v-else class="d-flex justify-content-center align-items-center">
          <div
            class="alert alert-warning d-flex justify-content-center align-items-center"
          >
            <span
              class="tavasi tavasi-warning-circle color-inherit ml-1 text__32"
            ></span>
            {{ $t("Inaccessibility") }}
          </div>
        </div>
      </no-data>

      <!-- <div class="card-body">
        <ul id="etrn" style="margin: 4%;">
          <li>
            <a href="http://pub.hamfahmi.ir/public">پوشه شخصی</a>
          </li>
          <li>
            <a href="http://pub.hamfahmi.ir/wiki">ویکی فرهنگستان</a>
          </li>
          <li>
            <a href="http://pub.hamfahmi.ir:91/">پرتال جامع پژوهشی</a>
          </li>
          <li>
            <a href="http://pub.hamfahmi.ir:94/">نرم افزار جامع پژوهشی-اداری</a>
          </li>
        </ul>
      </div> -->
    </div>
  </div>
</template>
<script>
import { mapActions, mapState } from "pinia";
import { useCommonStore } from "~/stores/commonStore";

export default {
  props: {
    layout: {
      default: "card",
    },
  },
  data() {
    return {
      systems: [],
      db: undefined,
      canView: false,
      fetchingData: false,
    };
  },
  computed: {
    ...mapState(useCommonStore, ["isSidebarCollapsed"]),
  },

  beforeCreate() {
    ApiService.init(import.meta.env.VITE_PERMIT_BASE_URL);
  },

  async mounted() {
    setTimeout(() => {
      this.checkPermisionBeforGetList();
    }, 500);
  },

  methods: {
    ...mapActions(useCommonStore, [
      "SET_USER_PERMISSIONS",
      "SET_AUTHORIZED_PAGES",
      "getSystems",
      "setBodyClass",
      "checkPermissions",
      "activeSystemSetter",
    ]),
    checkPermisionBeforGetList() {
      if (this.fetchingData) return;
      this.fetchingData = true;

      // this.checkPermissions({ permission: "my-systems_list", _this: this })
      // .then(() => {
      this.getSystems()
        .then((data) => {
          this.systems = data.filter(
            (item) => item.showInDashboard && !this.hamfahmiState(item)
          );
          this.canView = true;
        })
        .catch(() => {
          this.canView = false;
        })
        .finally(() => {
          this.fetchingData = false;
        });
      // })
      // .catch(() => {
      //   this.canView = false;
      //   this.fetchingData = false;
      // });
    },

    hamfahmiState(item = undefined) {
      if (buildName()() == "monir") {
        if (buildState()() == 1)
          if (item) return item.link != "chat" && item.link != "jahat";
      } else return false;
    },

    // async getDb() {
    //   const DB_NAME = "hamfahmi-table";
    //   const DB_VERSION = 1;

    //   return new Promise((resolve, reject) => {
    //     let request = window.indexedDB.open(DB_NAME, DB_VERSION);

    //     request.onerror = (e) => {
    //       console.log("Error opening db", e);
    //       reject("Error");
    //     };

    //     request.onsuccess = (e) => {
    //       resolve(e.target.result);
    //     };

    //     request.onupgradeneeded = (e) => {
    //       console.log("onupgradeneeded");
    //       let db = e.target.result;
    //       let objectStore = db.createObjectStore("projects-store", {
    //         autoIncrement: true,
    //         keyPath: "id",
    //       });
    //     };
    //   });
    // },
    // async getSystemsFromDb() {
    //   return new Promise((resolve, reject) => {
    //     let trans = this.db.transaction(["projects-store"], "readonly");
    //     trans.oncomplete = (e) => {
    //       resolve(systems);
    //     };

    //     let store = trans.objectStore("projects-store");
    //     let systems = [];

    //     store.openCursor().onsuccess = (e) => {
    //       let cursor = e.target.result;
    //       if (cursor) {
    //         systems.push(cursor.value);
    //         cursor.continue();
    //       }
    //     };
    //   });
    // },
    // async addCat() {
    //   this.addDisabled = true;
    //   // random cat for now
    //   let cat = {
    //     name: "Cat" + Math.floor(Math.random() * 100),
    //     age: Math.floor(Math.random() * 10) + 1,
    //   };
    //   console.log("about to add " + JSON.stringify(cat));
    //   await this.addToIdb(cat);
    //   this.systems = await this.getSystemsFromDb();
    //   this.addDisabled = false;
    // },
    // async addToIdb(cat) {
    //   return new Promise((resolve, reject) => {
    //     let trans = this.db.transaction(["projects-store"], "readwrite");
    //     trans.oncomplete = (e) => {
    //       resolve();
    //     };

    //     let store = trans.objectStore("projects-store");
    //     store.add(cat);
    //   });
    // },
    // async deleteCat(id) {
    //   await this.deleteFromIdb(id);
    //   this.systems = await this.getSystemsFromDb();
    // },
    // async deleteFromIdb(id) {
    //   return new Promise((resolve, reject) => {
    //     let trans = this.db.transaction(["projects-store"], "readwrite");
    //     trans.oncomplete = (e) => {
    //       resolve();
    //     };

    //     let store = trans.objectStore("projects-store");
    //     store.delete(id);
    //   });
    // },

    /*
    manually remvoe service worker
    */
    // async getDataFromServiceWorker() {
    //   if (indexDB) {
    //     return await readAllData("projects-store").then((data) => {
    //       // if (!networkDataRecieved) {
    //       // }
    //       return data;
    //     });
    //   }
    // },
    projectIcon(name) {
      try {
        if (name == "borhan") throw Error("load png icon instead.");
        else return import(`assets/common/img/logo/${name}.svg`).default;
      } catch (err) {
        try {
          return import(`assets/common/img/logo/${name}.jpg`).default;
        } catch (err) {
          return import("assets/common/img/default.svg").default;
        }
      }
    },
    redirectTo(project) {
      if (project.loading) return;
      project.loading = true;

      // clearBodyClass();
      this.activeSystemSetter(project);

      if (isValidHttpUrl(project.link)) {
        redirectToExternalLink(project.link, true);
        project.loading = false;
      } else {
        this.$router
          .push("/" + project.link)

          .then((res) => {
            project.loading = false;
          });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "assets/auth/signup";

.dashboard-bg {
  // background-image: url('../../../../assets/common/img/main-bg.png');
  background-size: 14em;
  background-position: center;
}

// .modules-selection-page {
//   .navbar {
//     margin-right: 0;

//     .sidebar-toggler {
//       display: none;
//     }
//   }
// }

.dashboard-page {
  height: calc(100vh - 4em);
  // height: calc(100vh - 0px);
  // overflow-y: auto;
  // display: flex;
  // padding: 2em 0;
  //background-color: #f7f7f7;

  .row {
    &.row-gap {
      row-gap: 2em;

      .lds-ring {
        margin-left: 0;
        position: absolute;
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        transform: scale(2);
      }
    }
  }

  .no-text-decoration {
    text-decoration: none;
  }

  &.horizontal {
    padding: 1em;
    .row {
      &.row-gap {
        row-gap: 1em;
      }
    }
  }
  &.list {
    height: auto;
    padding: 0em;
    .row {
      &.row-gap {
        row-gap: 0em;
      }
    }
  }
}
.card {
  background-color: unset !important;
}
</style>
