import { View } from "@tarojs/components";
import './Clock.scss'
import ClockNew from "./ClockNew";
import { useEffect, useState } from "react";
import Taro, { useShareAppMessage } from "@tarojs/taro";
import { useDispatch } from "react-redux";
import { getInfoSuccess } from "@/store/user";
import { useTranslation } from "react-i18next";

let useNavigation;

if (process.env.TARO_ENV == 'rn') {
    useNavigation = require("@react-navigation/native").useNavigation
}

export default function Clock() {
    const dispatch = useDispatch();
    const [loaded,setLoaded] = useState(false)
    const { t } = useTranslation()
    let navigation;
    if (useNavigation) {
        navigation = useNavigation()
    }


    if (process.env.TARO_ENV == 'weapp') {
        useShareAppMessage((e) => {
            return {
                title: t('feature.track_time_duration.common.share_title'),
                path: 'pages/clock/Clock'
            }
        })
    }
    
    useEffect(() => {
        if (navigation) {
            navigation.setOptions({
                headerTitle: '',
            });
        }
        global.memberAlert = false;
        if (process.env.TARO_ENV == 'weapp') {
            loadWXCache()
        }
        else {
            loadRNCache()
        }
    }, [])

    function loadWXCache() {
        var gps = Taro.getStorageSync('gps')
        if (gps) {
            global.locationDetail = JSON.parse(gps)
        }
        global.memberAlert = Taro.getStorageSync('memberAlert') || false
        var userData = Taro.getStorageSync('userData')
        if (userData) {
            dispatch(getInfoSuccess(JSON.parse(userData)));
        }
        setLoaded(true)
    }

    async function loadRNCache() {
        var showDayRing = await getStorage('showDayRing') || false;
        var showNightRing = await getStorage('showNightRing') || false;
        global.memberAlert = await getStorage('memberAlert') || false
        var gps = await getStorage('gps')
        if (gps) {
            global.locationDetail = JSON.parse(gps)
        }
        var userData = await getStorage('userData')
        console.log(userData)
        if (userData) {
            dispatch(getInfoSuccess(JSON.parse(userData)));
        }
        setLoaded(true)
    }

    async function getStorage(key: string) {
        try {
            const res = await Taro.getStorage({ key });
            return res.data;
        } catch {
            return '';
        }
    }

    if (!loaded)
        return <View />
    
    return <View style={{flex:1}}>
        <ClockNew />
    </View>
}