'use strict';

import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.7/firebase-app.js";
import { getDatabase, ref, set, onValue, child, get } from "firebase/database";

const firebaseConfig = {
apiKey: "AIzaSyD0853R7ElSWzvs_XmV-fQz7Gn6xQruByM",
authDomain: "zlext-e3506.firebaseapp.com",
projectId: "zlext-e3506",
storageBucket: "zlext-e3506.appspot.com",
messagingSenderId: "974590774477",
appId: "1:974590774477:web:3e4ed3716563a5935b6d84"
};

const app = initializeApp(firebaseConfig);

function writeUserData(userId, name, email, imageUrl) {
  const db = getDatabase();
  set(ref(db, 'users/' + userId), {
    username: name,
    email: email,
    profile_picture : imageUrl
  });
  .then(() => {
	  // Data saved successfully!
	})
	.catch((error) => {
	  // The write failed...
	});
}

function writeNewPost(uid, username, picture, title, body) {
  const db = getDatabase();

  const postData = {
    author: username,
    uid: uid,
    body: body,
    title: title,
    starCount: 0,
    authorPic: picture
  };

  const newPostKey = push(child(ref(db), 'posts')).key;

  const updates = {};
  updates['/posts/' + newPostKey] = postData;
  updates['/user-posts/' + uid + '/' + newPostKey] = postData;

  return update(ref(db), updates);
}


// const db = getDatabase();
// const starCountRef = ref(db, 'posts/' + postId + '/starCount');
// onValue(starCountRef, (snapshot) => {
  // const data = snapshot.val();
  // updateStarCount(postElement, data);
// });

// const dbRef = ref(getDatabase());
// get(child(dbRef, `users/${userId}`)).then((snapshot) => {
  // if (snapshot.exists()) {
    // console.log(snapshot.val());
  // } else {
    // console.log("No data available");
  // }
// }).catch((error) => {
  // console.error(error);
// });

