import React, { useEffect, Fragment, useContext } from 'react';
import Styled from 'styled-components/native';
import fetchGet, { fetchPost } from '~/Utils/fetch';
import session from '~/Utils/session';
import { useToast } from '~/Components/UIControls/Message';
import { NotificationUtil } from '~/Utils/notificationUtil';

const Verify = (props) => {
    const navigation = props.navigation;
    const { showMessage } = useToast();

    useEffect(() => {
        verify();
    }, []);

    const verify = async () => {
        try {
            await session.load();
        } catch(error) {
            navigation.navigate('LoginNavigator');
            return false;
        }

        if(!session.isAutoLogin()) {
            navigation.navigate('LoginNavigator');
            return false;
        }

        if(session.isLoggedIn()) {
            const userinfo = session.getUserInfo();
            console.log('previously logged in', userinfo);
            try {
                const siteinfo = session.getLoginSite();
                userinfo.SiteId = siteinfo.SiteId;
                userinfo.SiteName = siteinfo.SiteName;
                userinfo.BuildingId = siteinfo.BuildingId;
                userinfo.BuildingName = siteinfo.BuildingName;
                userinfo.ApiSido = siteinfo.ApiSido;
                userinfo.ApiSigun = siteinfo.ApiSigun;
                await session.setUserInfo(userinfo);
                await session.setSiteId(siteinfo.SiteId);

                const result = await fetchPost(`api/app/users/verify/${userinfo.SiteId}/${userinfo.UserId}`);
                const siteConfig = await fetchGet(`api/siteconfig`);
                await session.saveSiteConfig(siteConfig);
                const menus = await fetchGet(`api/sitemap/menu/2?siteId=${userinfo.SiteId}&userGroupId=${result.UserGroupId}`);
                await session.saveMenus(menus);
                console.log('saved menus length : ', menus.length);

                var error = await NotificationUtil.updatePushToken(userinfo.SiteId, userinfo.UserId);
                if(!!error) {
                    showMessage('푸시알림 등록실패 : ' + error);
                }
            } catch(error) {
                showMessage(error.message);
                console.log('login verify error : ', error);
                navigation.navigate('LoginNavigator');
                return false;
            }
            navigation.navigate('MainNavigator');
            return true;
        } else {
            navigation.navigate('LoginNavigator');
            return false;
        }
    };

    return (
        <Fragment />
    );
};

Verify.navigationOptions = {
    headerShown: false,
};

export default Verify;