import React, {useState, useEffect} from 'react';
import { LoginButton, AccessToken, LoginManager } from 'react-native-fbsdk';
import RNKakao from 'react-native-kakao';
import { NaverLogin, getProfile } from 'react-native-naver-login';
import { GoogleSignin, GoogleSigninButton, statusCodes } from 'react-native-google-signin';
import AsyncStorage from '@react-native-community/async-storage';



import C from 'rn-class'
C.addColor("#03cf5d", "color-naver");
GoogleSignin.configure({});
const initials = {
    kConsumerKey: 'VWv4bOdB5Bf07a26eJ5h',
    kConsumerSecret: 'pBASnpI7X5',
    kServiceAppName: 'empty',
    kServiceAppUrlScheme: 'naverorgseonsujoaemptyapp', // only for iOS
};


class Lm  {
    logout = async ()=>{
        let result = await  LoginManager.logOut();
        try {
            await GoogleSignin.revokeAccess();
            await GoogleSignin.signOut();
        } catch (error) {
            console.log(error)  
        }

        result = await RNKakao.logout();
        
        result = await NaverLogin.logout();
        
        AsyncStorage.removeItem("@naverToken");
        AsyncStorage.removeItem("@terms" );
        return true;
    }
}
const LM = new Lm()
export {
    LM
}

export default (props)=>{
    let callLogin = async (bfirst)=>{
        let rtn = {type : null, token : null, id : null };
        let fbData = await AccessToken.getCurrentAccessToken(); // 페이스북 
        if (fbData){
            rtn.type = "facebook"
            rtn.id = fbData.userID;  
            rtn.token = fbData.accessToken;
            props.onLogin && props.onLogin(rtn, bfirst); 
            return;
        }
        
        if(await GoogleSignin.isSignedIn()){
            try { 
                rtn.type = "google";
                rtn.token = (await GoogleSignin.getTokens()).accessToken; 
                rtn.id = (await GoogleSignin.getCurrentUser()).user.id; 
                props.onLogin && props.onLogin(rtn, bfirst);  
                return;   
            } catch (error) {}
        }


        let naverToken  = await  AsyncStorage.getItem("@naverToken");
        if(naverToken){
            let profile = await getProfile(naverToken);
            if(profile.resultcode =='00') {
                rtn.type = "naver";
                rtn.id = profile.response.id;
                rtn.token =  naverToken;
                props.onLogin && props.onLogin(rtn, bfirst); 
                return ;
            } 
        }

        try {
            const kakaoData = await RNKakao.userInfo();
            if (kakaoData){
                rtn.type = "kakao"
                rtn.id = kakaoData.id;
                rtn.token =  kakaoData.accessToken;
                props.onLogin && props.onLogin(rtn, bfirst); 
                return ;
            }

        } catch (error) {}

       
    }
    useEffect(()=>{
        callLogin();
        // console.log(dd);
    },[])
    // event fild
    let facebookLogin = async () =>{
        const result = await LoginManager.logInWithPermissions(['public_profile']);
        if(result ){
            callLogin(true);
        }
    }
    let googoleSignIn = async () =>{
        GoogleSignin.configure();
        try {
            if(await GoogleSignin.hasPlayServices()){
                const result = await GoogleSignin.signIn();  
                if(result){
                    callLogin(true);
                }
            }
        } catch (error) {
            if (error.code === statusCodes.SIGN_IN_CANCELLED) {
                    // user cancelled the login flow
                    console.log('cancel',error);
                } else if (error.code === statusCodes.IN_PROGRESS) {
                    // operation (f.e. sign in) is in progress already
                    console.log('progress',error);
                } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
                    // play services not available or outdated
                    console.log('service not available',error);
                } else {
                    // some other error happened
                    console.log(error)
                }
        }
    }
    let kakaoLogin = async () =>{
        const result = await RNKakao.login();
        if(result ){
            callLogin(true);token
        }
        props.onlogin && props.onlogin({type : "kakao", id : result.id , token : accessToken }, true);
    }
    let naverLogin = async () =>{
        
            NaverLogin.login(initials,  async (err, token) => {
                await  AsyncStorage.setItem("@naverToken", token);
                if(token){
                    callLogin(true);
                }
            });
    }
    let anonymousLogin = async () =>{

        // await  AsyncStorage.setItem("@anonymous", token);
        let rtn = {};
        rtn.type = "anonymous"
        rtn.id = "anonymous";
        rtn.token =  "anonymous";
        props.onLogin && props.onLogin(rtn, true); 
        return ;
        // NaverLogin.login(initials,  async (err, token) => {
        //     await  AsyncStorage.setItem("@naverToken", token);
        //     if(token){
        //         callLogin(true);
        //     }
        // });
    }



    return (
        <C.View  cls="jc-sa flx1">  
            <C.EL.Button btncls="bgc-color-facebook" title="Facebook" onPress={facebookLogin} />
            <C.EL.Button btncls="bgc-color-google-plus " title="Google" onPress={googoleSignIn} />
            <C.EL.Button btncls="bgc-color-kakao" tcls="color-kakaotext" title="Kakao" onPress={kakaoLogin}/>
            <C.EL.Button btncls="bgc-color-naver" title="Naver"  onPress={naverLogin} /> 

            <C.EL.Button btncls="bgc-color-gray-light-v1" title="Anonymous"  onPress={anonymousLogin} /> 

        </C.View> 

    )


}