<script>
import { defineComponent, computed, toRefs } from "vue";
import PageInfo from "../components/PageInfo";
import { resolvePage, outboundRE, endingSlashRE } from "../helpers/utils";
import { useInstance, useShowModule } from "../helpers/composable";
import MenuBar from "../components/MenuBar";

export default defineComponent({
  components: { PageInfo, MenuBar },

  props: ["sidebarItems"],
  render(h) {
    // let pageContent = {
    //   comp: "Content",
    //   dive: true,
    //   options: {
    //     // html: "./fr/introductionWbr2/index.js",
    //     class: "",
    //   },
    // };

    // if(this.$themeConfig.isWbMd||instance?.$route?.query?.isWbMd=='true')
    // pageContent = {
    //   comp: "MD",
    //   options: { class: "brown", src: this.$page.rawMarkdown },
    // };

    let wBCPageContentObj = {
      options: {
        key: this.instance.$store.state.lg,
        class: "page pa-15 ma-15",
        style: this.pageStyle,
      },

      default_1: {
        comp: MenuBar,
        options: { props: { class: "  pa-15 ma-15 can-hide" } },
      },
      default_2: [
        "<~div, page-title>",
        { comp: "h1", options: { class: "title", html: this.instance.$page.title } },
        {
          comp: PageInfo,
          options: {
            props: {
              pageInfo: this.instance.$page,
              showAccessNumber: this.showAccessNumber,
            },
          },
        },
      ],
      default_3: {
        comp: "section",
        dive: true,
        options: {
          directives: [{ name: "show", value: this.recoShowModule }],

          html: this.pageContent,
        },
      },

      default_4: {
        comp: "div",
        options: {
          directives: [
            { name: "show", value: this.recoShowModule && (this.prev || this.next) },
          ],
          class: "page-nav",

          html: [
            "<~p,inner>",

            "<~VRow,pa-1 ma-1>",

            {
              header: { en: "Previous:", fr: "précédent", ar: "السابق" },
              options: { html: this.prev?.title || "", to: this.prev?.path },
            },

            "VSpacer",
            {
              header: { en: "Next:", fr: "suivant", ar: "التالي" },
              options: { html: this.next?.title || "", to: this.next?.path },
            },
          ],
        },
      },
      ...(this?.$themeConfig?.pageStyle || {}),
    };


    return h("WBC", {
      props: { item: wBCPageContentObj },
    });

  },
  setup(props, ctx) {
    const instance = useInstance();

    const { sidebarItems } = toRefs(props);

    const recoShowModule = useShowModule();

    const shouldShowComments = computed(() => {
      const { isShowComments } = instance.$frontmatter;
      const { showComment } = instance.$themeConfig.valineConfig || { showComment: true };
      return (
        (showComment !== false && isShowComments !== false) ||
        (showComment === false && isShowComments === true)
      );
    });

    const showAccessNumber = computed(() => {
      const {
        $themeConfig: { valineConfig },
        $themeLocaleConfig: { valineConfig: valineLocalConfig },
      } = instance || {};

      const vc = valineLocalConfig || valineConfig;

      return vc && vc.visitor != false;
    });

    const lastUpdated = computed(() => {
      if (instance.$themeConfig.lastUpdated === false) return false;
      return instance.$page.lastUpdated;
    });

    const lastUpdatedText = computed(() => {
      if (typeof instance.$themeLocaleConfig.lastUpdated === "string") {
        return instance.$themeLocaleConfig.lastUpdated;
      }
      if (typeof instance.$themeConfig.lastUpdated === "string") {
        return instance.$themeConfig.lastUpdated;
      }
      return "Last Updated";
    });

    const prev = computed(() => {
      const frontmatterPrev = instance.$frontmatter.prev;
      if (frontmatterPrev === false) {
        return;
      } else if (frontmatterPrev) {
        return resolvePage(
          instance.$site.pages,
          frontmatterPrev,
          instance.$route?.path,
          instance.$store
        );
      } else {
        return resolvePrev(instance.$page, sidebarItems.value);
      }
    });

    const next = computed(() => {
      const frontmatterNext = instance.$frontmatter.next;
      if (next === false) {
        return;
      } else if (frontmatterNext) {
        return resolvePage(
          instance.$site.pages,
          frontmatterNext,
          instance.$route?.path,
          instance.$store
        );
      } else {
        return resolveNext(instance.$page, sidebarItems.value);
      }
    });

    const editLink = computed(() => {
      if (instance.$frontmatter.editLink === false) {
        return false;
      }
      const {
        repo,
        editLinks,
        docsDir = "",
        docsBranch = "master",
        docsRepo = repo,
      } = instance.$themeConfig;

      if (docsRepo && editLinks && instance.$page.relativePath) {
        return createEditLink(
          repo,
          docsRepo,
          docsDir,
          docsBranch,
          instance.$page.relativePath
        );
      }
      return "";
    });

    const editLinkText = computed(() => {
      return (
        instance.$themeLocaleConfig.editLinkText ||
        instance.$themeConfig.editLinkText ||
        `Edit this page`
      );
    });

    const pageStyle = computed(() => {
      return instance.$showSubSideBar ? {} : { paddingRight: "0" };
    });


    const pageContent = computed(() => {

      let thePageContent = {
      comp: "Content",
      dive: true,
      options: {
        // html: "./fr/introductionWbr2/index.js",
        class: "",
      },
    };

    if(instance?.$themeConfig?.isWbMd||instance?.$route?.query?.isWbMd=='true')
    thePageContent = {
      comp: "MD",
      options: { src: instance.$page.rawMarkdown },
    };

      return thePageContent;
    });

    return {
      recoShowModule,
      shouldShowComments,
      showAccessNumber,
      lastUpdated,
      lastUpdatedText,
      prev,
      next,
      editLink,
      editLinkText,
      pageStyle,
      instance,
      pageContent
    };
  },
});

function createEditLink(repo, docsRepo, docsDir, docsBranch, path) {
  const bitbucket = /bitbucket.org/;
  if (bitbucket.test(repo)) {
    const base = outboundRE.test(docsRepo) ? docsRepo : repo;
    return (
      base.replace(endingSlashRE, "") +
      `/src` +
      `/${docsBranch}/` +
      (docsDir ? docsDir.replace(endingSlashRE, "") + "/" : "") +
      path +
      `?mode=edit&spa=0&at=${docsBranch}&fileviewer=file-view-default`
    );
  }

  const base = outboundRE.test(docsRepo) ? docsRepo : `https://github.com/${docsRepo}`;

  return (
    base.replace(endingSlashRE, "") +
    `/edit` +
    `/${docsBranch}/` +
    (docsDir ? docsDir.replace(endingSlashRE, "") + "/" : "") +
    path
  );
}

function resolvePrev(page, items) {
  return find(page, items, -1);
}

function resolveNext(page, items) {
  return find(page, items, 1);
}

function find(page, items, offset) {
  const res = [];
  flatten(items, res);
  for (let i = 0; i < res.length; i++) {
    const cur = res[i];
    if (cur.type === "page" && cur?.path === decodeURIComponent(page?.path)) {
      return res[i + offset];
    }
  }
}

function flatten(items, res) {
  for (let i = 0, l = items.length; i < l; i++) {
    if (items[i].type === "group") {
      flatten(items[i].children || [], res);
    } else {
      res.push(items[i]);
    }
  }
}
</script>

<style lang="stylus">
@require '../styles/wrapper.styl'

.page
  position relative
  padding-top 5rem
  padding-bottom 2rem
  padding-right 14rem
  display block
  .page-title
    max-width: $contentWidth;
    margin: 0 auto;
    padding: 1rem 2.5rem;
    color var(--text-color)
  .theme-reco-content h2
    position relative
    padding-left 0.8rem
    &::before
      position absolute
      left 0
      top 3.5rem
      display block
      height 1.8rem
      content ''
      border-left 5px solid $accentColor
  .page-edit
    @extend $wrapper
    padding-top 1rem
    padding-bottom 1rem
    overflow auto
    .edit-link
      display inline-block
      a
        color $accentColor
        margin-right 0.25rem
    .last-updated
      float right
      font-size 0.9em
      .prefix
        font-weight 500
        color $accentColor
      .time
        font-weight 400
        color #aaa
  .comments-wrapper
    @extend $wrapper

.page-nav
  @extend $wrapper
  padding-top 1rem
  padding-bottom 0
  .inner
    min-height 2rem
    margin-top 0
    border-top 1px solid var(--border-color)
    padding-top 1rem
    overflow auto // clear float
  .next
    float right

@media (max-width: $MQMobile)
  .page
    padding-right 0
    .page-title
      padding: 0 1rem;
    .page-edit
      .edit-link
        margin-bottom .5rem
      .last-updated
        font-size .8em
        float none
        text-align left
</style>
