/*!
 * Copyright (c) 2021 Eclipse Foundation, Inc.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v. 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0.
 *
 * Contributors:
 *   Zhou fang <zhou.fang@eclipse-foundation.org>
 *
 * SPDX-License-Identifier: EPL-2.0
 */

import getMembers from '../api/eclipsefdn.members';
import template from './templates/explore-members/member-detail.mustache';
import { SD_IMG, AP_IMG, AS_IMG } from './eclipsefdn.constants.js';
import { validateURL } from '../api/utils';
import { getMonthName } from '../shared/utils';

const EclipseFdnMemberDetail = (async () => {
  const element = document.querySelector('.member-detail');
  if (!element) {
    return;
  }

  const orgId = new URL(window.location.href).searchParams.get('member_id');

  const errHandler = () =>
    (element.innerHTML = `
      <div class="col-md-14 col-lg-16 margin-bottom-30">
        <h1 class="red">INVALID MEMBER ID</h1>
        <p>No member could be found matching that ID.  There are three possible reasons
        why this can happen:</p>
        <ul>
          <li>You reached this page through a bad link (malformed HTML),</li>
          <li>this organization is no longer an active member,</li>
          <li>OR, this organization has not yet setup their membership page.</li>
        </ul>
        <p>Please <a href="mailto:membership@eclipse.org">email us</a> if you believe this
        is an error we can fix or better yet --
        <a href="https://bugs.eclipse.org/bugs/enter_bug.cgi?product=Community&amp;version=unspecified&amp;component=Website&amp;   rep_platform=PC&amp;op_sys=Windows%20XP&amp;priority=P3&amp;bug_severity=normal&amp;bug_status=NEW&amp;   bug_file_loc=http%3A%2F%2F&amp;short_desc=Eclipse%20Membership%20Pages%20Suggestion%20or%20Issue&amp;comment=&amp;   commentprivacy=0&amp;maketemplate=Remember%20values%20as%20bookmarkable%20template&amp;form_name=enter_bug&amp;  cc=membership%40eclipse.org">open a bug</a>.</p>
      </div>

      <div class="col-md-9 col-lg-7 col-md-offset-1 margin-top-20 margin-bottom-20">
        <div class="icon-sidebar-menu row">
            <div class="padding-bottom-20 clearfix">
              <div class="col-md-9 hidden-xs hidden-sm">
                <a class="circle-icon" href="/membership/exploreMembership.php">
                  <i class="fa fa-search orange"></i>
                </a>
              </div>
              <div class="col-sm-24 col-md-15">
                <h3><a href="/membership/exploreMembership.php">Explore our Members</a></h3>
                <p>Learn more about the products and services provided by the members of Eclipse</p>
              </div>
            </div>
            <div class="padding-bottom-20 clearfix margin-bottom-15">
              <div class="col-xs-8 col-md-9 hidden-xs hidden-sm">
                <a class="circle-icon" href="/membership/become_a_member/">
                  <i class="fa fa-user orange"></i>
                </a>
              </div>
              <div class="col-sm-24 col-md-15">
                <h3><a href="/membership/become_a_member/">Become a member</a></h3>
                <p>Join the Eclipse Foundation and influence the future</p>
              </div>
            </div>
            <div class="padding-bottom-20 clearfix">
              <div class="col-xs-8 col-md-9 hidden-xs hidden-sm">
                <a class="circle-icon" href="/membership/become_a_member/">
                  <i class="fa fa-question-circle orange"></i>
                </a>
              </div>
              <div class="col-sm-24 col-md-15">
                <h3><a href="/membership/faq/">Membership FAQs</a></h3>
                <p>Answers to questions frequently asked by, and about, membership</p>
              </div>
            </div>
        </div>
      </div>
    `);

  if (!orgId || !Number(orgId)) {
    // Show error message if member_id is missing or NOT a number
    errHandler('');
    return;
  }

  let pool = [
    getMembers(`https://membership.eclipse.org/api/organizations/${orgId}`, [], errHandler),
    getMembers(`https://membership.eclipse.org/api/organizations/${orgId}/projects`, [], errHandler),
    getMembers(`https://membership.eclipse.org/api/organizations/${orgId}/products`, [], errHandler),
  ];
  let memberDetailData = await Promise.all(pool);
  memberDetailData = { ...memberDetailData[0][0], projects: memberDetailData[1], products: memberDetailData[2] };

  const getMemberLevelImg = function () {
    const levels = this.levels;
    if (levels.find((item) => item.level?.toUpperCase() === 'SD')) {
      return SD_IMG;
    }
    if (levels.find((item) => item.level?.toUpperCase() === 'AP' || item.level?.toUpperCase() === 'OHAP')) {
      return AP_IMG;
    }
    if (levels.find((item) => item.level?.toUpperCase() === 'AS')) {
      return AS_IMG;
    }
  };

  const shouldShowLinksSideBar = function () {
    if (this.products?.length > 0 || this.projects?.length > 0) {
      return true;
    }
    return false;
  };

  element.innerHTML = template({
    memberSince: function() {
      const date = new Date(this.member_since);
      return `${getMonthName(date)} ${date.getFullYear()}`;
    },
    section: memberDetailData,
    getMemberLevelImg,
    shouldShowLinksSideBar,
    validateURL: () => validateURL(memberDetailData.website),
    trimDescription: function () {
      const description = this.description?.long || '';
      return description ? description.replaceAll('\\r\\n', '').replaceAll('\\', '') : '';
    },
  });
})();

export default EclipseFdnMemberDetail;
