"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const prop_types_1 = __importDefault(require("prop-types"));
const react_1 = __importDefault(require("react"));
const react_native_1 = require("react-native");
const components_1 = require("../../themes/components");
// @ts-ignore
const react_native_parsed_text_1 = __importDefault(require("react-native-parsed-text"));
const react_native_communications_1 = __importDefault(require("react-native-communications"));
const utils_1 = require("./utils");
const FS_1 = __importDefault(require("../FS"));
const FileViewer_1 = __importDefault(require("../FileViewer"));
const WWW_URL_PATTERN = /^www\./i;
const textStyle = {
    fontSize: 16,
    lineHeight: 20,
    marginTop: 5,
    marginBottom: 5,
    marginLeft: 10,
    marginRight: 10,
};
const styles = {
    left: react_native_1.StyleSheet.create({
        container: {},
        text: Object.assign({ color: 'black' }, textStyle),
        link: {
            color: 'black',
            textDecorationLine: 'underline',
        },
    }),
    right: react_native_1.StyleSheet.create({
        container: {},
        text: Object.assign({ color: 'white' }, textStyle),
        link: {
            color: 'white',
            textDecorationLine: 'underline',
        },
    }),
};
const DEFAULT_OPTION_TITLES = ['Call', 'Text', 'Cancel'];
class MessageText extends react_1.default.Component {
    constructor(props) {
        super(props);
        this.state = { downloading: null };
        this.onUrlPress = (url) => {
            // When someone sends a message that includes a website address beginning with "www." (omitting the scheme),
            // react-native-parsed-text recognizes it as a valid url, but Linking fails to open due to the missing scheme.
            if (WWW_URL_PATTERN.test(url)) {
                this.onUrlPress(`http://${url}`);
            }
            else {
                react_native_1.Linking.canOpenURL(url).then((supported) => {
                    if (!supported) {
                        console.error('No handler for URL:', url);
                    }
                    else {
                        react_native_1.Linking.openURL(url);
                    }
                });
            }
        };
        this.onPhonePress = (phone) => {
            const { optionTitles } = this.props;
            const options = optionTitles && optionTitles.length > 0
                ? optionTitles.slice(0, 3)
                : DEFAULT_OPTION_TITLES;
            const cancelButtonIndex = options.length - 1;
            this.context.actionSheet().showActionSheetWithOptions({
                options,
                cancelButtonIndex,
            }, (buttonIndex) => {
                switch (buttonIndex) {
                    case 0:
                        react_native_communications_1.default.phonecall(phone, true);
                        break;
                    case 1:
                        react_native_communications_1.default.text(phone);
                        break;
                    default:
                        break;
                }
            });
        };
        this.viewAttachedFile = (path, fileName) => __awaiter(this, void 0, void 0, function* () {
            this.setState({ downloading: true });
            try {
                const localFile = `${FS_1.default.DocumentDirectoryPath}/${fileName}`;
                const options = {
                    fromUrl: path,
                    toFile: localFile,
                };
                yield FS_1.default.downloadFile(options).promise;
                yield FileViewer_1.default.open(localFile, { showOpenWithDialog: true });
            }
            catch (e) {
                console.log('Error:', e);
                react_native_1.Alert.alert('Error', 'Unable to open attached file', [
                    { text: 'OK' },
                ]);
            }
            this.setState({ downloading: false });
        });
        this.onEmailPress = (email) => react_native_communications_1.default.email([email], null, null, null, null);
        this.onAttachemenetPress = (link, text) => this.viewAttachedFile(link, text);
        this.state = { downloading: false };
    }
    shouldComponentUpdate(nextProps, nextAppState) {
        return (this.state.downloading !== nextAppState.downloading ||
            (!!this.props.currentMessage &&
                !!nextProps.currentMessage &&
                this.props.currentMessage.text !==
                    nextProps.currentMessage.text));
    }
    render() {
        var _a, _b;
        const linkStyle = [
            styles[this.props.position].link,
            this.props.linkStyle && this.props.linkStyle[this.props.position],
        ];
        return (react_1.default.createElement(react_native_1.View, { style: [
                styles[this.props.position].container,
                this.props.containerStyle &&
                    this.props.containerStyle[this.props.position],
                {
                    display: 'flex',
                    flexDirection: 'row',
                    paddingHorizontal: 5,
                    justifyContent: 'space-between',
                },
            ] },
            react_1.default.createElement(react_native_parsed_text_1.default, { style: [
                    styles[this.props.position].text,
                    this.props.textStyle &&
                        this.props.textStyle[this.props.position],
                    this.props.customTextStyle,
                    ((_a = this.props.currentMessage) === null || _a === void 0 ? void 0 : _a.link) ? { width: '75%' } : {},
                ], parse: [
                    ...this.props.parsePatterns(linkStyle),
                    {
                        type: 'url',
                        style: linkStyle,
                        onPress: this.onUrlPress,
                    },
                    {
                        type: 'phone',
                        style: linkStyle,
                        onPress: this.onPhonePress,
                    },
                    {
                        type: 'email',
                        style: linkStyle,
                        onPress: this.onEmailPress,
                    },
                ], childrenProps: Object.assign({}, this.props.textProps) }, this.props.currentMessage.text),
            ((_b = this.props.currentMessage) === null || _b === void 0 ? void 0 : _b.link) && (react_1.default.createElement(react_native_1.TouchableOpacity, { style: {
                    justifyContent: 'center',
                }, onPress: () => this.onAttachemenetPress(this.props.currentMessage.link, this.props.currentMessage.text) }, !this.state.downloading ? (react_1.default.createElement(components_1.Icon, { boxSize: "26", name: "download-circle", fill: "textPrimary.100" })) : (react_1.default.createElement(components_1.Spinner, { color: "#fff", size: "small" }))))));
    }
}
exports.default = MessageText;
MessageText.contextTypes = {
    actionSheet: prop_types_1.default.func,
};
MessageText.defaultProps = {
    position: 'left',
    optionTitles: DEFAULT_OPTION_TITLES,
    currentMessage: {
        text: '',
    },
    containerStyle: {},
    textStyle: {},
    linkStyle: {},
    customTextStyle: {},
    textProps: {},
    parsePatterns: () => [],
};
MessageText.propTypes = {
    position: prop_types_1.default.oneOf(['left', 'right']),
    optionTitles: prop_types_1.default.arrayOf(prop_types_1.default.string),
    currentMessage: prop_types_1.default.object,
    containerStyle: prop_types_1.default.shape({
        left: utils_1.StylePropType,
        right: utils_1.StylePropType,
    }),
    textStyle: prop_types_1.default.shape({
        left: utils_1.StylePropType,
        right: utils_1.StylePropType,
    }),
    linkStyle: prop_types_1.default.shape({
        left: utils_1.StylePropType,
        right: utils_1.StylePropType,
    }),
    parsePatterns: prop_types_1.default.func,
    textProps: prop_types_1.default.object,
    customTextStyle: utils_1.StylePropType,
};
//# sourceMappingURL=MessageText.js.map