import * as React from "react";
import {View} from 'react-native';
import {NavigationContainer} from "@react-navigation/native";
import {CardStyleInterpolators, createStackNavigator} from '@react-navigation/stack';
import {INavScreen, NavScreenData, NavScreenType, NavScreenTypeData} from "./nav";
import {loggerConfig} from "./config";


const logger = loggerConfig('Screen');

class Screen implements INavScreen {
    private initialRouteName: string
    private readonly list: NavScreenData[]

    constructor(initialRouteName?: string) {
        this.initialRouteName = initialRouteName ?? '';
        this.list = [];
    }

    type: NavScreenType = {
        default: 0,
        fade: 1
    };

    set(pageName: string, component: any, type?: NavScreenTypeData): void {
        type = typeof type === "undefined" ? this.type.default : type;
        this.list.push({name: pageName, component, type});
    }

    setInitialRouteName(routeName: string): void {
        this.initialRouteName = routeName;
    }

    end(): React.ReactNode {
        if (this.initialRouteName.length === 0 || typeof this.initialRouteName !== "string") {
            logger.err('end()', '未设置初始化页面，请执行 setInitialRouteName 方法');
            return <View/>
        }
        const Stack = createStackNavigator();
        return <NavigationContainer>
            <Stack.Navigator initialRouteName={this.initialRouteName}
                             screenOptions={() => ({
                                 // 不显示导航
                                 headerShown: false,
                                 cardStyleInterpolator: CardStyleInterpolators.forHorizontalIOS,
                                 gestureEnabled: true,
                             })}
            >
                {
                    this.list.map((item, key) => {
                        let options = {};
                        if (item.type === 1) options = {
                            cardStyleInterpolator: ({current}) => ({
                                cardStyle: {
                                    opacity: current.progress,
                                }
                            })
                        };
                        return <Stack.Screen
                            key={key}
                            name={item.name}
                            component={item.component}
                            options={options}
                        />
                    })
                }
            </Stack.Navigator>
        </NavigationContainer>;
    }
}

export default Screen
export type {
    INavScreen, NavScreenData, NavScreenType, NavScreenTypeData
}
