function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import React, { Component } from "react";
import { Text } from "@plusscommunities/pluss-core-app/components";
import { Platform, Linking, StyleSheet, View, TouchableOpacity, ScrollView } from "react-native";
import { connect } from "react-redux";
import _ from "lodash";
import * as Calendar from "expo-calendar";
import { TEXT_DARK, getMainBrandingColourFromState } from "../colours";
import { InlineButton } from "./InlineButton";
import { Popup } from "./Popup";
import { MiddlePopup } from "./MiddlePopup";
const DEFAULT_TITLE = "Add to Calendar";
const ERROR_EVENT_ADD = "There was a problem adding a calendar event.";

// Required: eventToAdd
// Documentation: https://docs.expo.dev/versions/latest/sdk/calendar/#event
class AddToCalendarButton extends Component {
  constructor(props) {
    super(props);
    _defineProperty(this, "showWarningPopup", () => {
      if (Platform.OS !== "ios") return;
      this.setState({
        showPermissionWarning: true
      });
    });
    _defineProperty(this, "closeWarningPopup", () => {
      this.setState({
        showPermissionWarning: false
      });
    });
    _defineProperty(this, "goToPermissionSettings", () => {
      Linking.openURL("app-settings:");
      this.setState({
        showPermissionWarning: false
      });
    });
    _defineProperty(this, "onAdd", async () => {
      if (!this.props.eventToAdd) {
        this.setState({
          message: "There is no event to add"
        });
        return;
      }
      const {
        status
      } = await Calendar.requestCalendarPermissionsAsync();
      if (status !== "granted") {
        this.showWarningPopup();
      } else {
        let calendars = await Calendar.getCalendarsAsync(Calendar.EntityTypes.EVENT);
        // console.log('all calendars', calendars);
        if (calendars && calendars.length > 0) {
          calendars = calendars.filter(c => c.allowsModifications).map(c => {
            return {
              id: c.id,
              title: c.title,
              source: c.source.name,
              color: c.color,
              type: c.type
            };
          });
          calendars = _.orderBy(calendars, ["source", "title"]);
          // console.log('sorted calendars', calendars);
        }
        this.setState({
          calendars
        });
      }
    });
    _defineProperty(this, "onCloseCalendars", () => {
      this.setState({
        calendars: null
      });
    });
    _defineProperty(this, "onSelectCalendar", async calendar => {
      try {
        const {
          eventToAdd
        } = this.props;
        if (!eventToAdd) return;
        const eventId = await Calendar.createEventAsync(calendar.id, eventToAdd);
        this.setState({
          calendars: null,
          message: eventId ? `${eventToAdd.title} was added to ${calendar.title} successfully.` : ERROR_EVENT_ADD
        });
      } catch (error) {
        console.log("onSelectCalendar", error);
        this.setState({
          calendars: null,
          message: ERROR_EVENT_ADD
        });
      }
    });
    _defineProperty(this, "onCloseMessage", () => {
      this.setState({
        message: null
      });
    });
    this.state = {
      showPermissionWarning: false,
      calendars: null,
      message: null
    };
  }
  renderPermission() {
    return /*#__PURE__*/React.createElement(Popup, {
      title: "Permissions missing",
      text: "You must grant access to the Calendars. Tap Go to settings to change your permission settings.",
      options: [{
        text: "Go to settings",
        action: this.goToPermissionSettings,
        bold: true
      }, {
        text: "Ignore",
        action: this.closeWarningPopup
      }]
    });
  }
  renderCalendars(calendars) {
    return /*#__PURE__*/React.createElement(MiddlePopup, {
      style: [styles.calendarsPopup, {
        height: calendars.length * 60 + 120
      }],
      onClose: this.onCloseCalendars
    }, /*#__PURE__*/React.createElement(Text, {
      style: styles.calendarPopupTitle
    }, "Select Calendar"), /*#__PURE__*/React.createElement(View, {
      style: styles.calendarPopupContainer
    }, /*#__PURE__*/React.createElement(ScrollView, {
      style: {
        flex: 1
      },
      showsVerticalScrollIndicator: false
    }, calendars.map(cal => {
      return /*#__PURE__*/React.createElement(TouchableOpacity, {
        key: cal.id,
        onPress: () => this.onSelectCalendar(cal)
      }, /*#__PURE__*/React.createElement(View, {
        style: [styles.calendarContainer, {
          backgroundColor: cal.color
        }]
      }, /*#__PURE__*/React.createElement(Text, {
        style: styles.calendarText
      }, `${cal.source}${cal.source === cal.title ? "" : `\n${cal.title}`}`)));
    })), /*#__PURE__*/React.createElement(TouchableOpacity, {
      key: "cancel",
      onPress: this.onCloseCalendars
    }, /*#__PURE__*/React.createElement(View, {
      style: [styles.calendarContainer, {
        marginTop: 20,
        backgroundColor: this.props.colourBrandingMain
      }]
    }, /*#__PURE__*/React.createElement(Text, {
      style: styles.calendarText
    }, "Cancel")))));
  }
  renderMessage(message) {
    return /*#__PURE__*/React.createElement(Popup, {
      title: "Add to Calendar",
      text: message,
      options: [{
        text: "Ok",
        action: this.onCloseMessage
      }]
    });
  }
  render() {
    const {
      showPermissionWarning,
      calendars,
      message
    } = this.state;
    if (showPermissionWarning) return this.renderPermission();
    if (calendars && calendars.length > 0) return this.renderCalendars(calendars);
    if (message) return this.renderMessage(message);
    return /*#__PURE__*/React.createElement(InlineButton, _extends({}, this.props, {
      onPress: this.onAdd
    }), this.props.children || DEFAULT_TITLE);
  }
}
const styles = StyleSheet.create({
  calendarsPopup: {
    width: 250,
    maxHeight: 400,
    padding: 16,
    borderRadius: 12
  },
  calendarPopupTitle: {
    fontFamily: "sf-bold",
    color: TEXT_DARK,
    fontSize: 18,
    marginBottom: 16
  },
  calendarPopupContainer: {
    flex: 1,
    justifyContent: "space-between"
  },
  calendarContainer: {
    flexDirection: "row",
    alignItems: "center",
    width: 200,
    height: 40,
    paddingHorizontal: 8,
    borderRadius: 4,
    marginBottom: 10
  },
  calendarText: {
    color: "#fff",
    textAlign: "center",
    fontFamily: "sf-semibold",
    fontSize: 13,
    flex: 1
  }
});
const mapStateToProps = state => {
  return {
    colourBrandingMain: getMainBrandingColourFromState(state)
  };
};
const button = connect(mapStateToProps, {})(AddToCalendarButton);
export { button as AddToCalendarButton };
//# sourceMappingURL=AddToCalendarButton.js.map