import CalendarUtils from '@dvn/core/util/calendar';
import { Component, Event, h, Host, Prop, State } from '@stencil/core';
import { mentornityUpcomingMeetingWidgetI18nDefault, MentornityUpcomingMeetingWidgetI18nKey } from './i18n';
export class MentornityUpcomingmeetingsWidget {
  constructor() {
    this.toggleSeeAllButton = false;
    this.isPending = true;
    this.goToMeetingDetails = (meeting) => this.action.emit({
      name: 'go-to-meeting-page',
      params: { meetingId: meeting._id }
    });
  }
  async componentWillLoad() {
    this.strings = await this.apiSozluk.getContent(MentornityUpcomingMeetingWidgetI18nKey, mentornityUpcomingMeetingWidgetI18nDefault);
  }
  render() {
    const { meetings, timeFormat, strings, isPending, meetingGoalConfig, account, groupId } = this;
    const hasMeetings = (meetings === null || meetings === void 0 ? void 0 : meetings.length) > 0;
    if (isPending) {
      return (h(Host, null,
        h("b", { class: "pl-3", style: { fontSize: '1.1rem' } }, strings.upcomingMeetings),
        h("dvn-card", { elevation: 1 },
          h("div", { class: "d-flex justify-content-center" },
            h("dvn-progress", { indefinite: true, tint: "primary" })))));
    }
    return (h(Host, null,
      h("b", { class: "pl-3", style: { fontSize: '1.1rem' } }, strings.upcomingMeetings),
      h("dvn-card", { elevation: 1 },
        meetings &&
          generateUpcomingmeetingView(meetings, account, groupId, timeFormat, meetingGoalConfig, this.toggleSeeAllButton, strings, this.goToMeetingDetails),
        (meetings === null || meetings === void 0 ? void 0 : meetings.length) > 3 && !this.toggleSeeAllButton &&
          h("dvn-card-footer", { class: "mt-3", slot: "footer", alignRight: true },
            h("dvn-button", { leaned: true, view: "flat", onClick: () => {
                this.toggleSeeAllButton = true;
              } },
              strings.seeAll,
              "(",
              meetings.length,
              ")")),
        !hasMeetings &&
          h("div", { class: "col-md-12" },
            h("p", null,
              " ",
              strings.listMeetingsHere,
              " "),
            h("p", null,
              " ",
              strings.emptyMeetings,
              " ")))));
  }
  static get is() { return "mentornity-upcoming-meetings-widget"; }
  static get originalStyleUrls() { return {
    "$": ["mentornity-upcoming-meetings-widget.scss"]
  }; }
  static get styleUrls() { return {
    "$": ["mentornity-upcoming-meetings-widget.css"]
  }; }
  static get properties() { return {
    "meetings": {
      "type": "any",
      "mutable": false,
      "complexType": {
        "original": "any",
        "resolved": "any",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "meetings",
      "reflect": false
    },
    "account": {
      "type": "any",
      "mutable": false,
      "complexType": {
        "original": "any",
        "resolved": "any",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "account",
      "reflect": false
    },
    "groupId": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "group-id",
      "reflect": false
    },
    "isPending": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Boolean",
        "resolved": "Boolean",
        "references": {
          "Boolean": {
            "location": "global"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "defaultValue": "true"
    },
    "meetingGoalConfig": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "MeetingGoalConfig",
        "resolved": "MeetingGoalConfig",
        "references": {
          "MeetingGoalConfig": {
            "location": "import",
            "path": "src/modules/mentornity-js-client/models"
          }
        }
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "timeFormat": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "String",
        "resolved": "String",
        "references": {
          "String": {
            "location": "global"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "apiSozluk": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "SozlukApi",
        "resolved": "SozlukApi",
        "references": {
          "SozlukApi": {
            "location": "import",
            "path": "@dvn/sozluk/api"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    }
  }; }
  static get states() { return {
    "toggleSeeAllButton": {},
    "strings": {}
  }; }
  static get events() { return [{
      "method": "action",
      "name": "action",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "any",
        "resolved": "any",
        "references": {}
      }
    }]; }
}
const generateUpcomingmeetingView = (meetings, account, groupId, timeFormat, meetingGoalConfig, expandMeetings, strings, goToMeetingDetails) => {
  var _a;
  const hasMeetingGoal = meetingGoalConfig && ((_a = meetingGoalConfig.meetingGoals) === null || _a === void 0 ? void 0 : _a.length) > 0;
  // filter nearest meetings
  meetings = meetings.sort((a, b) => {
    return a.startDate * 1000 - b.startDate * 1000;
  });
  const generatedMeetings = generateMeetings(meetings, expandMeetings);
  return (h("div", null, generatedMeetings.map((meeting, i) => {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j;
    const meetingDate = CalendarUtils.format(new Date(meeting.startDate * 1000), 'MMM DD');
    const startDate = CalendarUtils.format(new Date(meeting.startDate * 1000), `ddd HH:mm ${timeFormat === '12-hour' ? 'A' : ''}`);
    const endDate = CalendarUtils.format(new Date(meeting.endDate * 1000), `HH:mm ${timeFormat === '12-hour' ? 'A' : ''}`);
    const guests = meeting.guests;
    const mentor = guests[0];
    const mentee = guests[1];
    const isAccountMentor = mentor._id === account._id;
    const isMenteeUser = mentee._class === 'users' || mentee.firstName;
    const isMenteeGroup = mentee._class === 'groups' || !mentee.firstName;
    const isAccountMenteeInMeeting = isMenteeUser && !!guests.find(m => m._id === account._id);
    const isGroupMenteeInMeeting = isMenteeGroup && groupId && !!guests.find(m => m._id === groupId); // eslint-disable-line max-len
    let fullName = '';
    if (account && isAccountMentor) {
      if (isMenteeUser) {
        fullName = `${mentee.firstName} ${mentee.lastName}`;
      }
      else if (isMenteeGroup) {
        if (((_a = meeting.guests) === null || _a === void 0 ? void 0 : _a.length) > 2) {
          for (let i = 1; i < ((_b = meeting.guests) === null || _b === void 0 ? void 0 : _b.length); i++) {
            fullName += meeting.guests[i].title;
            fullName = ((_c = meeting.guests) === null || _c === void 0 ? void 0 : _c.length) - 1 !== i
              ? fullName.concat(', ')
              : fullName;
          }
          fullName = truncate(fullName, 40);
        }
        else {
          fullName = mentee.title;
        }
      }
    }
    else if (account && (isAccountMenteeInMeeting || isGroupMenteeInMeeting)) {
      fullName = `${mentor.firstName} ${mentor.lastName}`;
    }
    const meetingTime = startDate + ' - ' + endDate;
    const displayBreakLine = i < (meetings === null || meetings === void 0 ? void 0 : meetings.length) - 1;
    const meetingLocation = `${((_e = (_d = meeting.location) === null || _d === void 0 ? void 0 : _d.type) === null || _e === void 0 ? void 0 : _e.charAt(0).toUpperCase()) + ((_g = (_f = meeting.location) === null || _f === void 0 ? void 0 : _f.type) === null || _g === void 0 ? void 0 : _g.slice(1))} ${((_j = (_h = meeting.location) === null || _h === void 0 ? void 0 : _h.type) === null || _j === void 0 ? void 0 : _j.toLowerCase()) === 'zoom' ? '' : strings.meet}`;
    const ownSession = hasMeetingGoal && (meetingGoalConfig === null || meetingGoalConfig === void 0 ? void 0 : meetingGoalConfig.meetingGoals.find(session => session.identifier === meeting.meetingGoalIdentifier));
    return (h("div", null,
      hasMeetingGoal &&
        h("div", { class: "meeting-goal-title" },
          h("h3", null,
            " ", ownSession === null || ownSession === void 0 ? void 0 :
            ownSession.meetingTitle,
            " ")),
      h("div", { class: "d-flex justify-content-between align-items-center mt-2" },
        h("div", { class: "d-flex meeting-data" },
          h("p", { class: "meeting-date", onClick: () => goToMeetingDetails(meeting) },
            " ",
            h("span", null, meetingDate),
            " "),
          h("div", { class: "flex-column ml-3" },
            h("div", { class: "full-name" },
              h("p", null,
                " ",
                fullName,
                " ")),
            h("div", { class: "meeting-time" },
              h("p", null,
                " ",
                meetingTime,
                " ")),
            h("div", { class: "d-flex align-items-center text-primary" }, meeting.location.type === 'custom' ?
              h("p", { class: "custom-address" },
                " ",
                truncate(meeting.location.address, 30),
                " ")
              :
                h("div", { class: "d-flex align-items-center" },
                  h("dvn-icon", { "icon-name": "uil uil-video", scale: "large", size: 20, class: "video-icon" }),
                  h("a", { class: "ml-2", target: '_blank', href: meeting.location.address },
                    " ",
                    meetingLocation,
                    " "))))),
        h("dvn-icon", { onClick: () => goToMeetingDetails(meeting), class: "clickable", "icon-name": "uil uil-angle-right-b", size: 35 })),
      displayBreakLine &&
        h("hr", { class: "break-line" })));
  })));
};
const generateMeetings = (meetings, toggleSeeAllButton) => {
  if (!meetings)
    return [];
  // display only first 3 items
  if (!toggleSeeAllButton) {
    return meetings.slice(0, 3);
  }
  // display all item
  return meetings;
};
const truncate = (text, limit) => {
  if (text.length > limit) {
    return text.substring(0, limit) + '...';
  }
  return text;
};
