/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

import React from 'react';
import {ActionSheetProvider} from '@expo/react-native-action-sheet'
import {AsyncStorage, Platform, StyleSheet} from 'react-native';
import {
    createAppContainer,
    createBottomTabNavigator,
    createDrawerNavigator,
    createStackNavigator,
    createSwitchNavigator
} from 'react-navigation';
import OneSignal from 'react-native-onesignal';
import Connect from "./screens/login/Connect";
import SplaSplashScreen from "./screens/splashscreen/SplashScreen";
import HelpMenu from "./screens/help/HelpMenu";
import Help from "./screens/help/Help";
import ForgottenPassword from "./screens/login/ForgottenPassword";
import TypeChoiser from "./screens/login/TypeChoiser";
import CreateUserStep2 from "./screens/login/createUserStep2";
import createAccount from "./screens/login/createAccount";
import UpdateInformations from "./screens/account/UpdateInformations";
import UserAccount from "./screens/account/UserAccount";
import ActivateAccount from "./screens/login/ActivateAccount";
import Notifications from "./screens/notifications/Notifications";
import About from "./screens/configurations/About";
import Configurations from "./screens/configurations/Configurations";
import OptionsMenu from "./screens/optionMenu/OptionsMenu";
import Home from "./screens/home/Home";
import HistoryItemDetails from "./screens/history-request/HistoryItemDetails";
import SuperViseurGroupeHome from "./screens/groupes/SuperViseurGroupeHome";
import HistoryRequester from "./screens/history-request/HistoryRequester";
import AddNetwork from "./screens/account/AddNetwork";
import MyHistory from "./screens/history-request/MyHistory";
import Icon from "react-native-vector-icons/FontAwesome5";
import I18n from "react-native-i18n";

import WalletDetail from './screens/wallet/WalletDetail';
import WalletSelect from './screens/wallet/WalletSelect';
import {PersistGate} from 'redux-persist/integration/react';
import {persistor, store} from './redux/store';
import {Provider} from 'react-redux';
import WalletDepot from './screens/wallet/WalletDepot';
import WalletRetrait from './screens/wallet/WalletRetrait';
import CreateIdentification from './screens/identification/createIdentification';
import WalletDetailUser from './screens/wallet/WalletDetailUser';
import WalletOptionSelect from './screens/wallet/WalletOptionSelect';
import ValidateIdentification from './screens/identification/validateIdentification';
import CreateIdentificationUser from './screens/identification/CreateIdentificationUser';
import OperateurOptionSelect from './screens/wallet/OperateurOptionSelect';
import PaiementFacture from './screens/wallet/PaiementFacture';
import EnvoieWalletToWalletUser from './screens/wallet/user/EnvoieWalletToWalletUser';
import EnvoieWalletToCashUser from './screens/wallet/user/EnvoieWalletToCash';
import LinkCard from './screens/wallet/user/LinkCard';
import EnvoieWalletToCardUser from './screens/wallet/user/EnvoieWalletToCardUser';
import EnvoieWalletToBankUser from './screens/wallet/user/EnvoieWalletToBankUser';
import RetraitWalletVersCashUser from './screens/wallet/user/RetraitWalletVersCashUser';
import RetraitCarteVersCashUser from './screens/wallet/user/RetraitCarteVersCashUser';
import RetraitCarteVersWalletUser from './screens/wallet/user/RetraitCarteVersWalletUser';
import RetraitEnCashAgent from './screens/wallet/agent/RetraitEnCashAgent';
import RetraitCarteVersCashAgent from './screens/wallet/agent/RetraitCarteVersCashAgent';
import EnvoieCashVersWalletAgent from './screens/wallet/agent/EnvoieCashVersWalletAgent';
import EnvoieCashVersAutreWalletAgent from './screens/wallet/agent/EnvoieCashVersAutreWalletAgent';
import EnvoieCashVersCarteAgent from './screens/wallet/agent/EnvoieCashVersCarteAgent';
import EnvoiCashVersCashAgent from './screens/wallet/agent/EnvoiCashVersCashAgent';
import ModifyIdentificationUser from './screens/identification/ModifyIdentificationUser';
import CreateGroupNanoCredit from './screens/nano-credit/CreateGroupNanoCredit';
import DemandValidationGroup from './screens/nano-credit/DemandGroupNanoCredit';
import DemandGroupNanoCreditDetail from './screens/nano-credit/DemandGroupNanoCreditDetail';
import AdhererGroupNanoCredit from './screens/nano-credit/AdhererGroupNanoCredit';
import MyNanoCreditGroup from './screens/nano-credit/MyNanoCreditGroup';
import AskNanoCredit from './screens/nano-credit/AskNanoCredit';
import RefundNanoCreditUser from './screens/nano-credit/RefundNanoCreditUser';
import CautionNanoCreditAgent from './screens/nano-credit/CautionNanoCreditAgent';
import EpargnerArgentUser from './screens/nano-credit/EpargnerArgentUser';
import CasserEpargneUser from './screens/nano-credit/CasserEpargneUser';
import {IlinkEmitter} from './utils/events';
import EnvoieWalletToBankAgent from "./screens/wallet/agent/EnvoieWalletToBankAgent";
import ReattachAccountUser from "./screens/wallet/user/ReattachAccountUser";


const instructions = Platform.select({
    ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
    android:
        'Double tap R on your keyboard to reload,\n' +
        'Shake or press menu button for dev menu',
});

const theme = require("./utils/theme")

const AuthStack = createStackNavigator({
    login: Connect,
    helpMenu: HelpMenu,
    help: Help,
    forgottenpass: ForgottenPassword,
    typeaccountcreate: TypeChoiser,
    simpleusercreate: createAccount,
    step2: CreateUserStep2,
    activateaccout: ActivateAccount

}, {
    headerMode: 'none'
})
const AppStack = createDrawerNavigator({
    sta: createStackNavigator({
        home: Home,
        /* filtre:Filter,
         network:Networks,*/
        useraccount: {
            screen: UserAccount,
            navigationOptions: {},
        },
        walletSelect: WalletSelect,
        createIdentificationUser: CreateIdentificationUser,
        modifyIdentificationUser: ModifyIdentificationUser,
        notificationview: Notifications,
        configuration: Configurations,
        about: About,
        walletDetailUser: WalletDetailUser,
        walletOptionSelect: WalletOptionSelect,
        operateurOptionSelect: OperateurOptionSelect,
        paiementFacture: PaiementFacture,
        envoieWalletToWalletUser: EnvoieWalletToWalletUser,
        envoieWalletToCashUser: EnvoieWalletToCashUser,
        envoieWalletToCardUser: EnvoieWalletToCardUser,
        envoieWalletToBankUser: EnvoieWalletToBankUser,
        retraitWalletVersCashUser: RetraitWalletVersCashUser,
        retraitCarteVersCashUser: RetraitCarteVersCashUser,
        retraitCarteVersWalletUser: RetraitCarteVersWalletUser,
        linkCard: LinkCard,
        reattachAccountUser: ReattachAccountUser,
        epargnerArgentUser: EpargnerArgentUser,
        createGroupNanoCredit: CreateGroupNanoCredit,
        groupNanoCredit: {
            screen: createBottomTabNavigator({
                demandeValidationGroupe: {
                    screen: DemandValidationGroup,
                    navigationOptions: {
                        tabBarLabel: I18n.t('DEMAND_VALIDATION_GROUP_RECEIVE'),
                        tabBarIcon: ({focused, horizontal, tintColor}) => {
                            return (<Icon
                                size={20}
                                name={"users-cog"}
                                color={focused ? tintColor : "grey"}
                            />)
                        }
                    }
                },
                myNanoCreditGroup: {
                    screen: MyNanoCreditGroup,
                    navigationOptions: {
                        tabBarLabel: I18n.t('MY_GROUP'),
                        tabBarIcon: ({focused, horizontal, tintColor}) => {
                            return (<Icon
                                size={20}
                                name={"users"}
                                color={focused ? tintColor : "grey"}
                            />)
                        }
                    }
                },
            }, {
                headerMode: "none",
                header: null,
                headerTitle: null,
                title: I18n.t('MANAGE_GROUP'),
                tabBarOptions: {
                    labelStyle: {
                        fontSize: 13,
                    },
                }
            }),
            navigationOptions: () => ({
                header: null,
                headerMode: 'none',
                headerTitle: null,
                activeColor: '#f0edf6',
                inactiveColor: '#3e2465',
                barStyle: {backgroundColor: '#694fad'},

                drawerLabel: I18n.t('MANAGE_GROUP'),
                drawerIcon: ({tintColor}) => (
                    <Icon
                        name={'account-multiple'}
                        size={24}
                    />)
            }),
        },
        demandeValidationGroupe: DemandGroupNanoCreditDetail,
        adhererGroupNanoCredit: AdhererGroupNanoCredit,
        askNanoCredit: AskNanoCredit,
        refundNanoCreditUser: RefundNanoCreditUser,
        casserEpargneUser: CasserEpargneUser

    })
}, {
    contentComponent: OptionsMenu,
    headerMode: 'none',
    contentOptions: {activeTintColor: theme.accent}
})

const AppAgentStack = createDrawerNavigator({
    sta: createStackNavigator({
        home: Home,
        useraccount: UserAccount,
        walletSelect: WalletSelect,
        createIdentification: CreateIdentification,
        validateIdentification: ValidateIdentification,
        Historique:
            {
                screen: createBottomTabNavigator({myDemand: MyHistory}, {
                    headerMode: "none",
                    header: null,
                    headerTitle: I18n.t('CREDIT_MANAGE'),
                    tabBarOptions: {
                        labelStyle: {
                            fontSize: 13,
                            fontWeight: "bold"
                        },
                    }
                }),
                navigationOptions: () => ({
                    header: null,
                    headerMode: 'none',
                    headerTitle: null,
                    activeColor: '#f0edf6',
                    inactiveColor: '#3e2465',
                    barStyle: {backgroundColor: '#694fad'},
                    /* headerLeft: (<HeaderBackButton />), */
                    drawerLabel: I18n.t('CREDIT_MANAGE'),
                    drawerIcon: ({tintColor}) => (
                        <Icon
                            name={'credit-card'}
                            size={24}
                        />)
                }),
            },

        historyItemDetails: HistoryItemDetails,
        creditrequest: HistoryRequester,
        addNetwork: AddNetwork,
        updateinformation: UpdateInformations,
        notificationview: Notifications,
        configuration: Configurations,
        about: About,
        walletDetail: WalletDetail,
        walletDepot: WalletDepot,
        walletRetrait: WalletRetrait,
        walletOptionSelect: WalletOptionSelect,
        operateurOptionSelect: OperateurOptionSelect,
        paiementFacture: PaiementFacture,
        retraitEnCashAgent: RetraitEnCashAgent,
        retraitCarteVersCashAgent: RetraitCarteVersCashAgent,
        envoieCashVersWalletAgent: EnvoieCashVersWalletAgent,
        envoieCashVersAutreWalletAgent: EnvoieCashVersAutreWalletAgent,
        envoieCashVersCarteAgent: EnvoieCashVersCarteAgent,
        envoiCashVersCashAgent: EnvoiCashVersCashAgent,
        envoieWalletToBankAgent: EnvoieWalletToBankAgent,
        createGroupNanoCredit: CreateGroupNanoCredit,
        cautionNanoCreditAgent: CautionNanoCreditAgent,
    })
}, {
    contentComponent: OptionsMenu,
    backBehavior: "none",
    lazy: false,
    headerMode: 'none', contentOptions: {activeTintColor: theme.accent}
});

const AppAdministratorStack = createDrawerNavigator({
        sta: createStackNavigator({
            home: Home,
            useraccount: UserAccount,
            walletSelect: WalletSelect,
            Historique: {
                screen: createBottomTabNavigator({
                    myDemand: MyHistory, OthersDemand: MyHistory
                }, {
                    headerMode: "none",
                    header: null,
                    headerTitle: null,
                    title: I18n.t('CREDIT_MANAGE'),
                    tabBarOptions: {
                        labelStyle: {
                            fontSize: 13,
                        },
                    }
                }),
                navigationOptions: () => ({
                    header: null,
                    headerMode: 'none',
                    headerTitle: null,
                    activeColor: '#f0edf6',
                    inactiveColor: '#3e2465',
                    barStyle: {backgroundColor: '#694fad'},

                    drawerLabel: I18n.t('CREDIT_MANAGE'),
                    drawerIcon: ({tintColor}) => (
                        <Icon
                            name={'credit-card'}
                            size={24}
                        />)
                }),
            },
            creditrequest: HistoryRequester,
            historyItemDetails: HistoryItemDetails,

            superviseurgroup: SuperViseurGroupeHome,
            notificationview: Notifications,
            configuration: Configurations,
            about: About,
            walletDetail: WalletDetail,
            walletDepot: WalletDepot,
            walletRetrait: WalletRetrait

        })
    },
    {
        contentComponent: OptionsMenu,
        backBehavior: "none",
        headerMode: 'none'
    });

const AppSuperAdministrator = createDrawerNavigator({
    sta: createStackNavigator({
        home: Home,
        useraccount: UserAccount,
        walletSelect: WalletSelect,
        Historique: {
            screen: createBottomTabNavigator({OthersDemand: MyHistory}, {
                headerMode: "none",
                header: null,
                headerTitle: null,
                title: I18n.t('CREDIT_MANAGE'),
                tabBarOptions: {
                    labelStyle: {
                        fontSize: 13,
                        fontWeight: "bold"
                    },
                }
            }),
            navigationOptions: () => ({
                title: I18n.t('CREDIT_MANAGE'),
                headerMode: "none",
                header: null,
                headerTitle: null,
                drawerIcon: ({tintColor}) => (
                    <Icon
                        name={'credit-card'}
                        size={24}
                    />)
            }),
        },
        creditrequest: HistoryRequester,
        historyItemDetails: HistoryItemDetails,
        superviseurgroup: SuperViseurGroupeHome,
        notificationview: Notifications,
        configuration: Configurations,
        about: About,
        walletDetail: WalletDetail,
        walletDepot: WalletDepot,
        walletRetrait: WalletRetrait

    })
}, {
    contentComponent: OptionsMenu,
    backBehavior: "none",
    headerMode: 'none'
});

const AppNavigator = createSwitchNavigator({
    first: {
        screen: SplashScreen
    },
    App: AppStack,
    AgentApp: AppAgentStack,
    adminApp: AppAdministratorStack,
    supAdminApp: AppSuperAdministrator,
    Auth: AuthStack
}, {
    initialRouteName: 'first'
});
const AppContainer = createAppContainer(AppNavigator);

export default class AppIos extends React.Component {

    constructor(props) {
        super(props);
        console.log("APP PROPS", this.props);
        global.appHasLoaded = false;
        //Remove this method to stop OneSignal Debugging
        OneSignal.setLogLevel(6, 0);
        IlinkEmitter.on("langueChange", this.updateLangue.bind(this))
        // Replace 'YOUR_ONESIGNAL_APP_ID' with your OneSignal App ID.
        OneSignal.init("e8e7251f-713d-4658-9510-86d877fa6a7c", {
            kOSSettingsKeyAutoPrompt: false,
            kOSSettingsKeyInAppLaunchURL: false,
            kOSSettingsKeyInFocusDisplayOption: 2
        });
        OneSignal.inFocusDisplaying(2); // Controls what should happen if a notification is received while the app is open. 2 means that the notification will go directly to the device's notification center.

        // The promptForPushNotifications function code will show the iOS push notification prompt. We recommend removing the following code and instead using an In-App Message to prompt for notification permission (See step below)
        OneSignal.promptForPushNotificationsWithUserResponse(myiOSPromptCallback);

        OneSignal.addEventListener('received', this.onReceived);
        OneSignal.addEventListener('opened', this.onOpened);
        OneSignal.addEventListener('ids', this.onIds);
    }

    updateLangue() {
        this.forceUpdate()
    }

    _getOneSignalIds = () => {
        return new Promise(async (resolve, reject) => {
            try {
                const getElement = await AsyncStorage.getItem('@config:onesignalIds');
                resolve(getElement);
            } catch (error) {
                reject(error);
            }
        });
    }

    _saveOneSignalIds = async (ids) => {
        try {
            await AsyncStorage.setItem('@config:onesignalIds', ids);
        } catch (error) {
            console.warn(error);
        }
    }


    goToScreen = (routeName, params, isReset = true) => {
        const {navigator} = this.refs;
        if (typeof navigator !== 'undefined') {
            console.log("APP HAS LOADED", global.appHasLoaded);
            if (global.appHasLoaded) {

                navigator.dispatch({
                    type: "Navigation/NAVIGATE",
                    routeName,
                    params
                });
                /*                     readUser().then((result) => {
                                         if (result === null || result === undefined) {
                                              console.warn("APP HAS LOADED NOTIFICATION PARAMS", params);

                                              navigator.dispatch({
                                                   type: "Navigation/NAVIGATE",
                                                   routeName: "first",
                                                   params: { routeName, params }
                                              });
                                         } else {
                                              navigator.dispatch({
                                                   type: "Navigation/NAVIGATE",
                                                   routeName,
                                                   params
                                              });
                                         }
                                    }); */
            } else {
                navigator.dispatch({
                    type: "Navigation/NAVIGATE",
                    routeName: "first",
                    params: {routeName, params}
                });
            }
        }
    };

    handleDeepLink = (openResult) => {
        const data = openResult.notification.payload.additionalData;
        //const dataParse = data.replace("'", "\"");
        console.warn("HANDLE DEEP LINK", data);
        switch (data.screen) {
            case 'historyItemDetails':
                console.log("History Item");
                this.goToScreen(data.screen, {
                    item: data.data
                });
                break;

            default:
                console.log("Not History Item");
                this.goToScreen(data.screen, {
                    id: data.data.id
                });
                break;
        }

        /*           if (data && data.id) {
                       this.goToScreen(data.screen, {
                            id: data.id,
                            goToScreen: this.goToScreen
                       });
                  } else {
                       console.log("notification is invalid data");
                  } */
    };

    componentWillUnmount() {
        OneSignal.removeEventListener('received', this.onReceived);
        OneSignal.removeEventListener('opened', this.onOpened);
        OneSignal.removeEventListener('ids', this.onIds);
    }

    onReceived(notification) {
        console.log("Notification received: ", notification);
    }

    onOpened = (openResult) => {
        let data = openResult.notification.payload.additionalData;
        this.handleDeepLink(openResult);
        console.log('Message: ', openResult.notification.payload.body);
        console.log('Data: ', openResult.notification.payload.additionalData);
        console.log('isActive: ', openResult.notification.isAppInFocus);
        console.log('openResult: ', openResult);
    }

    render() {
        return (
            <Provider store={store}>
                <PersistGate persistor={persistor}>
                    <ActionSheetProvider>
                        <AppContainer ref="navigator"/>
                    </ActionSheetProvider>
                </PersistGate>
            </Provider>
        );
    }
}

function myiOSPromptCallback(permission) {
    // do something with permission value
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },
    welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
    },
    instructions: {
        textAlign: 'center',
        color: '#333333',
        marginBottom: 5,
    },
});
