import {getAuth,signInWithPopup, OAuthProvider,onAuthStateChanged } from "firebase/auth";
import {getUserInfo,createUser} from '@/app/util/db'
// import jwt_decode from "jwt-decode";
// import createUser from '../User/createUser';

import graphUrl from './graphUrl';
import photoUrl from './photoUrl';
import { initializeApp } from "firebase/app";
import Config from '../Firebase/Config'
const app = initializeApp(Config);
const auth = getAuth(app)

const provider = new OAuthProvider('microsoft.com');
function stringToHash(string) {
    var hash = 0;
    if (string.length == 0) 
        return hash;
    for (var i = 0; i < string.length; i++) {
        var char = string.charCodeAt(i);
        hash = ((hash << 5) - hash) + char;
        hash = hash & hash;
    }
    return hash;
}

const Microsoft = () => {
    return new Promise(async(resolve, reject) => {
        signInWithPopup(auth, provider).then(async(result) => {
            const credential = OAuthProvider.credentialFromResult(result);
            const accessToken = credential.accessToken;
            console.log(credential);
            console.log(credential.idToken);
            onAuthStateChanged(auth, async (user) => {
                if (user) {
                  const uid = user.uid;
                  await graphUrl(accessToken).then(async(response) => {
                    await getUserInfo(uid)
                    .then(async res=>{
                        if(res.length == 0) {
                            await createUser(uid, response.displayName,"Microsoft",response.mail).catch(err=>{
                                console.log(err)
                            })
                        }
                       resolve(uid)
                    }).catch(err=>{
                        reject(err.message)
                    })
                }).catch((error) => {
                    reject(error);
                })
                } else {
                 
                }
              });
           
            // const idToken = credential.idToken;   await createUser(user.uid,
            // user.displayName, idToken.email, 'google', user.photoURL).then((result) => {
            //   console.log(result) }) .catch((error) =>{     console.log(error) })
        }).catch((error) => {
        
            reject(error.message.replace('Firebase: ',''))
        });

    })
}

export default Microsoft