var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import React, { Component } from 'react';
import { AsyncStorage, ScrollView, Text, TouchableHighlight, TouchableOpacity, View } from 'react-native';
import { Modal } from './Modal';
import { style as S } from '../styles/SearchScreen';
import { SearchBar } from './SearchBar';
import FSI18n, { translationKeys } from '@brandingbrand/fsi18n';
const searchIcon = require('../../assets/images/search.png');
const SEARCH_MODAL_HISTORY_KEY = 'SEARCH_MODAL_HISTORY_KEY';
const MAX_HISTORY_ITEM_NUM = 5;
export class SearchModal extends Component {
    constructor(props) {
        super(props);
        this.loadHistoryToState = () => {
            this.getHistory()
                .then(history => {
                this.setState({ history, inputValue: '' });
            })
                .catch(e => console.warn(e));
        };
        this.getSearchBarRef = (ref) => {
            this.searchBar = ref;
        };
        this.getHistory = () => __awaiter(this, void 0, void 0, function* () {
            const historyData = (yield AsyncStorage.getItem(SEARCH_MODAL_HISTORY_KEY)) || '[]';
            try {
                const history = JSON.parse(historyData);
                return history.slice(0, MAX_HISTORY_ITEM_NUM);
            }
            catch (e) {
                yield AsyncStorage.setItem(SEARCH_MODAL_HISTORY_KEY, '[]');
                return [];
            }
        });
        this.addToHistory = (item) => __awaiter(this, void 0, void 0, function* () {
            let history = yield this.getHistory();
            const existIndex = history.findIndex(result => result.title === item.title);
            if (existIndex > -1) {
                history = history
                    .slice(0, existIndex)
                    .concat(history.slice(existIndex + 1));
                history.unshift(item);
            }
            else {
                history.unshift(item);
                history = history.slice(0, MAX_HISTORY_ITEM_NUM);
            }
            yield AsyncStorage.setItem(SEARCH_MODAL_HISTORY_KEY, JSON.stringify(history));
            return history;
        });
        this.handleResultPress = (result) => () => {
            this.addToHistory(result).catch(e => console.warn(e));
            if (this.props.onResultPress) {
                return this.props.onResultPress(result);
            }
        };
        this.handleSubmit = (value) => {
            this.addToHistory({
                title: value,
                query: value
            }).catch(e => console.warn(e));
            if (this.props.onInputSubmit) {
                return this.props.onInputSubmit(value);
            }
        };
        this.clearHistory = () => __awaiter(this, void 0, void 0, function* () {
            yield AsyncStorage.setItem(SEARCH_MODAL_HISTORY_KEY, '[]');
            this.setState({ history: [] });
        });
        this.renderHistory = () => {
            if (!this.state.history || !this.state.history.length) {
                return null;
            }
            return (<ScrollView style={S.resultsContainer} keyboardShouldPersistTaps='always' keyboardDismissMode='on-drag'>
        <View style={S.recentSearchContainer}>
          <Text style={S.recentSearch}>
            {FSI18n.string(translationKeys.flagship.search.recentSearches)}:
          </Text>

          <TouchableOpacity onPress={this.clearHistory} accessibilityLabel={FSI18n.string(translationKeys.flagship.search.actions.clear.accessibility)}>
            <Text style={S.recentSearchClearText}>
              {FSI18n.string(translationKeys.flagship.search.actions.clear.actionBtn)}
            </Text>
          </TouchableOpacity>
        </View>
        {this.state.history.map(this.renderItem)}
      </ScrollView>);
        };
        this.renderResult = () => {
            if (!this.props.results || !this.props.results.length) {
                if (this.props.results === null) {
                    return this.renderHistory();
                }
                else {
                    return null;
                }
            }
            return (<ScrollView style={S.resultsContainer} keyboardShouldPersistTaps='always' keyboardDismissMode='on-drag'>
        {this.props.results.map(this.renderItem)}
      </ScrollView>);
        };
        this.renderItem = (item, i) => {
            if (this.props.renderResultItem) {
                return this.props.renderResultItem(item, i, this.state.inputValue);
            }
            return (<TouchableHighlight key={i} underlayColor='#f8f8f8' style={[S.resultItem, this.props.itemStyle]} onPress={this.handleResultPress(item)} accessibilityLabel={`Search ${item.title}`}>
        {this.renderTextWithHighLighs(item.title, this.state.inputValue)}
      </TouchableHighlight>);
        };
        this.renderTextWithHighLighs = (name = '', query) => {
            const strArr = highlightStr(name, query);
            return (<Text style={[S.suggestionTitle, this.props.itemTextStyle]}>
        {strArr.map((str, i) => {
                return (<Text key={i} style={str.isHighlight && S.suggestionHighlight}>
              {str.str}
            </Text>);
            })}
      </Text>);
        };
        this.handleChange = (value) => {
            this.setState({ inputValue: value });
            if (this.props.onInputChange) {
                return this.props.onInputChange(value);
            }
        };
        this.renderSearchBar = () => {
            return (<View style={S.searchBarContainer}>
        <SearchBar ref={this.getSearchBarRef} onCancel={this.props.onClose} onSubmit={this.handleSubmit} onChange={this.handleChange} showSearchIcon={true} searchIcon={searchIcon} cancelButtonAlwaysVisible={true} {...this.props.searchBarProps}/>
      </View>);
        };
        this.state = {
            history: [],
            inputValue: ''
        };
    }
    componentDidMount() {
        this.loadHistoryToState();
    }
    componentDidUpdate(prevProps) {
        if (!prevProps.visible && this.props.visible) {
            setTimeout(() => {
                this.searchBar.focusInput();
            }, 100);
            this.loadHistoryToState();
        }
    }
    render() {
        return (<Modal visible={this.props.visible} animationType='fade' onRequestClose={this.props.onClose}>
        <View style={S.modalContainer}>
          {this.renderSearchBar()}
          {this.renderResult()}
        </View>
      </Modal>);
    }
}
function highlightStr(name, query) {
    let queryRegx;
    try {
        queryRegx = new RegExp(query, 'ig');
    }
    catch (e) {
        return [
            {
                str: name,
                isHighlight: false
            }
        ];
    }
    const matches = name.match(queryRegx);
    if (!matches || !query) {
        return [
            {
                str: name,
                isHighlight: false
            }
        ];
    }
    const textSplits = name.split(queryRegx).reduce((acc, item) => {
        if (item) {
            acc.result.push({
                str: item,
                isHighlight: false
            });
        }
        if (matches[acc.matchIndex]) {
            acc.result.push({
                str: matches[acc.matchIndex],
                isHighlight: true
            });
        }
        acc.matchIndex += 1;
        return acc;
    }, { result: [], matchIndex: 0 });
    return textSplits.result;
}
//# sourceMappingURL=SearchModal.js.map