/** * @format * @flow */ import React from "react"; import { View, Text, FlatList, StyleSheet, Alert, TouchableOpacity, Platform, ActivityIndicator, } from "react-native"; import NetInfo from "@react-native-community/netinfo"; import AsyncStorage from "@react-native-community/async-storage"; import { NavigationScreenProp, NavigationState } from "react-navigation"; import { widthPercentageToDP as wp, heightPercentageToDP as hp, } from "react-native-responsive-screen"; import { storeData, getFolderDataGameWise } from "common/asyncStorageHelper"; import strings from "res/strings"; import colors from "../../res/colors"; import { isLandscapeMode, isTablet, minH6, minSubtitle2, minSubtitle3, } from "../utils/DimensionUtils"; import { abbreviateName } from "../utils/PracticeSetUtils"; import StratagemClient from "../networking/StratagemClient"; import { StratagemData, NavParams, AuthTypes } from "../Enums"; import { InvalidUserCredentialsError } from "../Errors"; import LoadingOverlay from "./LoadingOverlay"; import ManageNavigation from "./ManageNavigation"; import { CURRENT_LEADERBOARD, CURRENT_DATASOURCE, CURRENT_INFODOC, CURRENT_PRACTICE_SET, CURRENT_PRACTICE_SET_KEYS, GAME_ID, } from "../../constants"; import _ from "lodash"; import { getGameId } from "../utils/CommonMethod"; import { StringShortener } from "../utils/textOrImageUtils"; // '../common/utils/CommonMethod'; const isLandscape = isLandscapeMode(); type Props = { style?: object; practiceSets: Array; stratagemClient: StratagemClient; isRecentlyPlayedFolder?: boolean; navigation: NavigationScreenProp | NavigationState; authType?: string; isPracticeSetEditable?: string; onClickSuccess: (practiceSet: string, practiceSetKeys: Array) => any; folderIDProp: string; }; type State = { isLoading: boolean; IsScrollBottomReached: Boolean; loadingIndicatorforExtraData: boolean; PracticeSetData: any[]; scrollBegin: boolean; isScrolled: boolean; }; type CaptionProps = { practiceSet: Object; }; export default class PracticeSetFolder extends React.Component { // TODO: CLIENT_AUTH default type for now static defaultProps = { style: {}, isRecentlyPlayedFolder: false, authType: AuthTypes.CLIENT_AUTH, isPracticeSetEditable: "", }; constructor(props: { style?: object; practiceSets: Array; stratagemClient: StratagemClient; isRecentlyPlayedFolder?: boolean; navigation: NavigationScreenProp | NavigationState; authType?: string; folderIDProp: string; onClickSuccess: ( practiceSetColor: string, practiceSetKeys: Array ) => any; }) { super(props); this.state = { isLoading: false, IsScrollBottomReached: false, PracticeSetData: [], loadingIndicatorforExtraData: false, scrollBegin: false, isScrolled: false, }; } componentDidMount() { const { practiceSets } = this.props; } /** * Abbreviates given name with the first letters of the first 2 words or the first two * letters of the lone word. ex) Aircraft Livery = AL; Callsigns = Ca */ abbreviateName = (name: string) => { const words = name.split(" "); let abbreviation = ""; if (words.length === 1) { const word = words[0]; if (word.length > 1) { abbreviation = words[0].substring(0, 2); } else { abbreviation = word; } } else { abbreviation = words[0].charAt(0) + words[1].charAt(0); } return abbreviation; }; // for Multigame case checkEmptyDataSet = (allDataSet, gameId) => { let isAnyDataValid = false; console.log("allDataSet ==> " + JSON.stringify(allDataSet)); allDataSet.forEach((dataSetFieldValues) => { // means data belog to multigame if ( dataSetFieldValues.questionType && dataSetFieldValues.questionType.length > 0 ) { if (dataSetFieldValues.questionType === "word") { if ( dataSetFieldValues.Question === null || dataSetFieldValues.Question === "" ) { isAnyDataValid = true; return true; } } else { // check for match and quizitive type for (const key in dataSetFieldValues) { // console.log('key ==> '+key); if ( dataSetFieldValues[key] === null || dataSetFieldValues[key] === "" ) { isAnyDataValid = true; return true; } } } } else { isAnyDataValid = true; // not found question type } }); return isAnyDataValid; }; checkInternetConnectivity = async (practiceSet: Object) => { NetInfo.addEventListener((state) => { if (state.isConnected === true) { this.getPracticeSetInOnlineMode(practiceSet); } else { this.isPracticeSetDataAvailable(practiceSet); } }); }; // check is Practice set data available for Offline mode case isPracticeSetDataAvailable = async (practiceSet: Object) => { const { navigation, authType } = this.props; const getGameHiddenDict = navigation.getParam(NavParams.IS_GAME_HIDDEN_API); const gameId = getGameId( navigation.getParam(NavParams.SELECTED_GAME), getGameHiddenDict ); // Set current practice set. This line is temporary and should be removed later await AsyncStorage.setItem( CURRENT_PRACTICE_SET, JSON.stringify(practiceSet) ); const recentlyPlayed = await AsyncStorage.getItem( StratagemData.RECENTLY_PLAYED ); if (recentlyPlayed !== null) { const recentlyPlayedArray = JSON.parse(recentlyPlayed); // check selected practice sets available in recentlyPlayed practice set or not const recordExist = recentlyPlayedArray.filter( (set) => set.dataSetID === practiceSet?.dataSetID ); if (recordExist.length > 0) { this.selectedPracticeSetRelatedData(practiceSet, authType, gameId); } else { Alert.alert(strings.offlineErrorMsg.netConnectionIssue); } } else { Alert.alert(strings.offlineErrorMsg.netConnectionIssue); } }; saveThisDataBasedOnPracticeSet = async (practiceSet: Object) => { if (practiceSet.leaderboardID) { const leaderboardData = await AsyncStorage.getItem( practiceSet.leaderboardID ); await AsyncStorage.setItem(CURRENT_LEADERBOARD, leaderboardData); } if (practiceSet.referenceID) { const infoDocData = await AsyncStorage.getItem(practiceSet.referenceID); await AsyncStorage.setItem(CURRENT_INFODOC, infoDocData); } const dataSet = await AsyncStorage.getItem(practiceSet.dataSetID); await AsyncStorage.setItem(CURRENT_DATASOURCE, dataSet); }; isMatchOrWordGameExist = (dataSetRecords) => { let isQuestionTypeExist = false; dataSetRecords.forEach((dataSetFieldValues) => { if ( dataSetFieldValues.questionType && dataSetFieldValues.questionType.length > 0 ) { if ( dataSetFieldValues.questionType === "match" || dataSetFieldValues.questionType === "word" ) { isQuestionTypeExist = true; } } }); return isQuestionTypeExist; }; isDataImproperOrNot = (dataSetRecords) => { let isImproperData = false; dataSetRecords.forEach((dataSetFieldValues) => { if ( dataSetFieldValues.questionType && dataSetFieldValues.questionType.length > 0 ) { if ( (dataSetFieldValues.questionType === "match" || dataSetFieldValues.questionType === "word") && dataSetFieldValues.fields && Object.keys(dataSetFieldValues.fields).length > 4 ) { isImproperData = true; } } }); return isImproperData; }; getPracticeSetInOnlineMode = async (practiceSet: Object) => { const { stratagemClient, navigation, authType } = this.props; const getGameHiddenDict = navigation.getParam(NavParams.IS_GAME_HIDDEN_API); let gameId = await AsyncStorage.getItem(GAME_ID); let anyError = false; // TODO handle offline data (user created/modified) console.log("" + JSON.stringify(practiceSet)); const dataSet = await stratagemClient.getDownloadDataSet( authType, gameId, practiceSet.dataSetID ); console.log("dataSet", dataSet); try { await AsyncStorage.setItem( CURRENT_PRACTICE_SET, JSON.stringify(practiceSet) ); if (authType === AuthTypes.CSV_PARSE) { this.saveThisDataBasedOnPracticeSet(practiceSet); } else { // import API DATA CALLS n then this.setState({ isLoading: true }); // Download all practice set related data into the DB const reference = await stratagemClient.downloadReference( authType, gameId, practiceSet.referenceID ? practiceSet.referenceID : practiceSet.referencesID ); this.setState({ isLoading: false }); if (!dataSet || !reference) { anyError = true; let errorMessage = "Unable to Load Practice set:\n"; errorMessage = dataSet ? errorMessage : errorMessage.concat("\nData Set"); errorMessage = reference ? errorMessage : errorMessage.concat("\nReference"); errorMessage = errorMessage.concat( "\n\nContinue to game with old data?" ); // TODO onPress continue, go to native game screen and send (old) data over const alertButtons = [ { text: "Cancel", onPress: () => {} }, { text: "Continue", onPress: () => {} }, ]; // There's a React Native iOS bug where if an alert appears while a modal is up, the alert // closes immediately and the modal can't be removed. This timeout works around that setTimeout( () => Alert.alert("Error", errorMessage, alertButtons), 10 ); } if (dataSet) { const alertButtons = [ { text: "Cancel", onPress: () => {} }, ]; if (dataSet.records) { if (dataSet.records.length === 0) { anyError = true; setTimeout( () => Alert.alert( "Error", strings.practiceSetRelatedError.insufficientData, alertButtons ), 50 ); } else if (dataSet.records.length === 1) { const isError = this.checkEmptyDataSet(dataSet.records, gameId); } // test improper data case // is Match or Word game data exist in data records const isWordMatchGame = this.isMatchOrWordGameExist( dataSet.records ); if (dataSet.records.length >= 1 && isWordMatchGame) { // console.log('outer data set length '+JSON.stringify(dataSet.records)); const isImproperData = this.isDataImproperOrNot(dataSet.records); if (isImproperData) { anyError = true; if (Platform.OS === "ios") { setTimeout( () => Alert.alert( strings.practiceSetRelatedError.improperDataSet ), 50 ); } else { setTimeout( () => alert(strings.practiceSetRelatedError.improperDataSet), 50 ); } } } } else { anyError = true; setTimeout( () => Alert.alert( "Error", "Practice Set is having no data.", alertButtons ), 50 ); } } } // Show error dialog if any of the data failed to download if (!anyError) { // Save pressed practice set in recently played list /* const recentlyPlayedArray = await getAllRecentlyPlayedData( gameId, authType ); if (recentlyPlayedArray !== null && recentlyPlayedArray.length > 0) */ console.log("check point 5"); const recentlyPlayed = await AsyncStorage.getItem( StratagemData.RECENTLY_PLAYED ); if (recentlyPlayed !== null) { const recentlyPlayedArray = JSON.parse(recentlyPlayed); // filter out all practice sets to not include the practice set that was just tapped const recentlyPlayedPracticeSets = recentlyPlayedArray.filter( (set) => set.dataSetID !== practiceSet.dataSetID ); // add tapped practice set to beginning recentlyPlayedPracticeSets.unshift(practiceSet); /* // delete all recent data, for authType basis deleteAllRecentlyPlayedDataAuthGameID(gameId, authType); // save all recent played data const recentUseData = JSON.stringify( recentlyPlayedPracticeSets.slice(0, 10) ); saveAllRecentlyPlayedDataGame(gameId, authType, recentUseData); */ // store 10 recently played practice sets await AsyncStorage.setItem( StratagemData.RECENTLY_PLAYED, JSON.stringify(recentlyPlayedPracticeSets.slice(0, 10)) ); } else { await AsyncStorage.setItem( StratagemData.RECENTLY_PLAYED, JSON.stringify([practiceSet]) ); // saveRecentlyPlayedDataGame(gameId, authType, practiceSet); } console.log("check point 6"); this.selectedPracticeSetRelatedData(practiceSet, authType, gameId); } // Get the keys for the matches in the practice set // console.log("error point"); } catch (error) { Alert.alert("Error", strings.practiceSetRelatedError.insufficientData); console.log( "issue on data download case ==> " + error, JSON.stringify(error) ); this.setState({ isLoading: false }); // if error was due to invalid credentials (meaning the user's password has been changed), // then go to login screen if (error instanceof InvalidUserCredentialsError) { const gameID = navigation.getParam(NavParams.GAME_ID); navigation.navigate("Login", { [NavParams.STRATAGEM_CLIENT]: stratagemClient, [NavParams.KEYCLOAK_CLIENT]: stratagemClient.keycloakClient, [NavParams.GAME_ID]: gameID, }); } } }; getFolderNameOnTheBasisOf = (folderId, childFolderArr) => { let childFolderName = ""; if (childFolderArr !== null) { childFolderArr.forEach((obj) => { if (obj.id === folderId) { childFolderName = obj.name; } }); } return childFolderName; }; addNestedFolderInPracticeSetArray = ( folder, practiceSetsInFolder, childFolderArr ) => { const nestedArr = []; // if multiple id within folder then create each for one, and it's visable as practice set folder.childFolders.forEach((objId) => { nestedArr.push({ folderID: objId, parentId: folder.id, folderName: this.getFolderNameOnTheBasisOf(objId, childFolderArr), }); }); practiceSetsInFolder.forEach((element) => { nestedArr.push(element); }); return [nestedArr]; }; onPressPracticeSet = async (practiceSet: Object) => { // get the folder Id // and check in folder array over that is it contain child folder array or not, // if contain get the id and get all the data from the practice set array, // and pass it to the next folder component, // check is internet available if true call the API // and false case return offline data if practice set already played // else Show the Alert message Unable to download this practice set. open net connection // check is practice set touchable or not if (ManageNavigation.getPracticeSetTouchableValue() === false) { try { const { navigation, practiceSets, isPracticeSetEditable } = this.props; let matchingPracticeSet = []; const gameId = getGameId(navigation.getParam(NavParams.SELECTED_GAME)); let folders = await getFolderDataGameWise(gameId); // Remove CSV_PARSE if condition when nested data fill in csv_parse data if (navigation.getParam(NavParams.AUTH_TYPE) !== AuthTypes.CSV_PARSE) { this.checkInternetConnectivity(practiceSet); // method added for dashboard data } else { // get data of selected practice Set and move to the homeScreen Component this.checkInternetConnectivity(practiceSet); } } catch (error) { Alert.alert( "Error", "An error occurred while loading Nested folder data" ); } } }; // call back of selected practice set related data selectedPracticeSetRelatedData = async ( practiceSet: Object, authType: string, gameID: string ) => { const { onClickSuccess } = this.props; const dataSetString = await AsyncStorage.getItem(practiceSet.dataSetID); storeData(CURRENT_DATASOURCE, dataSetString); let currentPracticeSetKeys = []; if (dataSetString) { const dataSet = JSON.parse(dataSetString); if ( dataSet && dataSet.records && dataSet.records[0] && dataSet.records[0].fields ) { currentPracticeSetKeys = Object.keys(dataSet.records[0].fields); } } this.setState({ isLoading: false }); /* save current Practice set and currentPracticeSetKeys for side menu, when user play game and come back to React Native part that case drawer view open for that data required */ await AsyncStorage.setItem( CURRENT_PRACTICE_SET, JSON.stringify(practiceSet) ); await AsyncStorage.setItem( CURRENT_PRACTICE_SET_KEYS, JSON.stringify(currentPracticeSetKeys) ); onClickSuccess(practiceSet, currentPracticeSetKeys); // navigate to tab page }; PracticeSetCaption = (props: CaptionProps) => ( {/* for nested folder pass folder name */} {props.practiceSet.name !== undefined ? StringShortener(props.practiceSet.name) : StringShortener(props.practiceSet.folderName)} {''} ); RecentlyPlayedPracticeSetCaption = (props: CaptionProps) => ( {props.practiceSet.name} {''} ); onEndReached = async () => { const { folderIDProp } = this.props; console.log("folderIDProp", folderIDProp); if (folderIDProp) { this.setState({ loadingIndicatorforExtraData: true }); const data: [] = await this.onRightEndReachedPulltoFetch(folderIDProp); this.addmorePStoCurrentFolder(data); this.setState({ loadingIndicatorforExtraData: false, isScrolled: true }); } }; addmorePStoCurrentFolder = (APIPracticeSetdata: []) => { const { practiceSets } = this.props; console.log("practiceSets->", practiceSets); console.log("APIPracticeSetdata->", APIPracticeSetdata); let result = _.unionBy(APIPracticeSetdata, practiceSets, "id"); console.log("result=>", result); this.setState({ PracticeSetData: result }); }; onRightEndReachedPulltoFetch = async (folderId: string) => { const { navigation } = this.props; let getOrgID; let orgData = navigation.getParam(NavParams.ORG_DATA); let gameID = await AsyncStorage.getItem(GAME_ID); const stratagemClient = navigation.getParam(NavParams.STRATAGEM_CLIENT); if (orgData && orgData !== undefined && orgData !== null) { getOrgID = orgData.id; } try { const response = await stratagemClient.fetchMorePSbyFolderByID( getOrgID, gameID, folderId ); this.setState({ loadingIndicatorforExtraData: false }); return response; } catch (e: any) { this.setState({ loadingIndicatorforExtraData: false }); console.log("e2", e); } }; render() { const { PracticeSetCaption, RecentlyPlayedPracticeSetCaption } = this; const { isLoading, PracticeSetData, loadingIndicatorforExtraData } = this.state; const { style, practiceSets, isRecentlyPlayedFolder } = this.props; return ( 0 ? PracticeSetData : practiceSets} keyExtractor={(item, index) => item.id !== undefined ? item.id.toString() : index.toString() } style={style} onMomentumScrollBegin={() => { this.setState({ scrollBegin: true }); }} onMomentumScrollEnd={() => { if (!this.state.isScrolled) { this.onEndReached(); } this.setState({ scrollBegin: false }); }} onEndReachedThreshold={0.5} renderItem={({ item, index }) => ( {/* the practice set button */} this.onPressPracticeSet(item)} // onPress={() => alert(JSON.stringify(item.color))} style={{ borderColor: colors.darkText, borderWidth: 1, borderRadius: 5, }} > {/* abbrev. */} {/* for nested folder pass folder name */} {abbreviateName( item.name !== undefined ? item.name : item.folderName )} {/* status */} {/* the caption, which is different if rendering recently played folder */} {isRecentlyPlayedFolder ? ( ) : ( )} )} ListEmptyComponent={ {isRecentlyPlayedFolder && ( none )} } /> {/* LoadingOverlay for when the practice set is tapped and data is being downloaded */} {isLoading && } {loadingIndicatorforExtraData && ( )} ); } } const styles = StyleSheet.create({ practiceSet: { flex: 1, flexDirection: "column", alignItems: "center", borderRadius: 5, }, practiceSetCaptionContainer: { width: isLandscape ? hp(21) : wp(21), height: Platform.OS === "android" ? 56 : 48, alignItems: "center", alignSelf: "center", justifyContent: "center", }, recentPracticeSetCaptionContainer: { width: isLandscape ? hp(21) : wp(21), height: Platform.OS === "android" ? 56 : 48, alignItems: "center", alignSelf: "center", justifyContent: "center", }, practiceSetName: { color: colors.lightText, fontSize: isTablet() ? isLandscape ? minH6(hp(1)) : minH6(hp(1)) : isLandscape ? minSubtitle3(hp(1)) : minSubtitle3(wp(1)), maxWidth: isLandscape ? hp(15) : wp(15), paddingTop: isLandscape ? hp(0.6) : wp(0.6), textAlign: "center", }, recentPracticeSetName: { color: colors.lightText, fontSize: isTablet() ? isLandscape ? minH6(hp(1)) : minH6(hp(1)) : isLandscape ? minSubtitle3(hp(1)) : minSubtitle3(wp(1)), maxWidth: isLandscape ? hp(15) : wp(15), paddingTop: isLandscape ? hp(0.6) : wp(0.6), textAlign: "center", }, recentFolderName: { color: colors.darkerText, fontSize: isLandscape ? minSubtitle2(hp(2)) : minSubtitle2(wp(2)), textAlign: "left", }, practiceSetButton: { fontFamily: "Montserrat-Medium", fontWeight: "500", alignItems: "center", textAlign: "center", backgroundColor: "#C00ADC", overflow: "hidden", color: colors.home.textDark, fontSize: isLandscape ? hp(5.5) : wp(5.5), width: isLandscape ? hp(13) : wp(13), height: isLandscape ? hp(13) : wp(13), borderRadius: 5, paddingTop: isLandscape ? hp(13 / 4) : wp(13 / 4), textTransform: "uppercase", }, PracticeBtnSubContainer: {}, practiceSetPlaceholder: { textAlign: "center", textAlignVertical: "center", backgroundColor: "#F7F9FA", color: colors.secondaryTextColor, fontSize: isLandscape ? hp(2) : wp(2), width: isLandscape ? hp(13) : wp(13), height: isLandscape ? hp(13) : wp(13), marginTop: hp(1), marginLeft: wp(5), marginRight: wp(1), borderRadius: 10, borderWidth: 2, borderColor: "black", borderStyle: "dashed", }, });