import { world, system } from "@minecraft/server";

const Event = {
  name: "playerSpawn",
  type: 1,
  run: async(data, db) => {
   if(!data.initialSpawn) return;
   
   db.push("playerStreak", data.player.name)
   
    data.player.nameTag = ` §8§l| §r${data.player.name}`;
    
    const now = new Date().toLocaleDateString();
    
    let streakdb = data.player.getDynamicProperty("streak")
    if(!streakdb) {
      data.player.setDynamicProperty('streak', 0)
      streakdb = data.player.getDynamicProperty("streak")
    }
    let datedb = data.player.getDynamicProperty("lastActive")
    if(!datedb) {
      data.player.setDynamicProperty('lastActive', now)
      datedb = data.player.getDynamicProperty("streak")
    }
    
    
 
     if(datedb !== now) {
    await system.waitTicks(20)
    data.player.onScreenDisplay.setTitle(`display:§r-`)
    
    await system.waitTicks(180)
    const diff = (new Date(now) - new Date(datedb)) / (1000 * 60 * 60 * 24);

    if (streakdb !== 0 && Math.floor(diff) > 1) {
      data.player.setDynamicProperty("streak", 0)
      data.player.setDynamicProperty("lastActive", now)
      
      //toast
        data.player.onScreenDisplay.setTitle(`toast:OFFStreak Destroyed!:/:§r${streakdb}-Day Streak`)
        await system.waitTicks(2)
        data.player.playSound("random.glass")
        
     } else {
       data.player.setDynamicProperty("streak", streakdb + 1);
       data.player.setDynamicProperty("lastActive", now)
       
       //toast
        data.player.onScreenDisplay.setTitle(`toast:LITStreak Up!:/:§r${data.player.getDynamicProperty("streak")}-Day Streak`)
        await system.waitTicks(2)
        data.player.playSound("random.levelup")
     }
     
     await system.waitTicks(200)
     data.player.onScreenDisplay.setTitle(`display:§r${data.player.getDynamicProperty("streak")}`)
     await system.waitTicks(5)
     data.player.onScreenDisplay.setTitle(`display.pet:cold`)
  } else {
    await system.waitTicks(20)
    data.player.onScreenDisplay.setTitle(`display:§r${data.player.getDynamicProperty("streak")}`)
    await system.waitTicks(5)
  //  data.player.onScreenDisplay.setTitle(`display.pet:cold`)
    }
    
    data.player.nameTag = `§l§6${data.player.getDynamicProperty('streak')} §8| §r${data.player.name}`;
  }
}


export default Event;