package dev.crucifixbeta.core.impl;

import dev.crucifixbeta.core.Manager;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.entity.player.PlayerEntity;
import org.apache.commons.io.IOUtils;

@Environment(EnvType.CLIENT)
public class FriendManager extends Manager {
   public final ArrayList<String> friendList = new ArrayList<>();
   private boolean paused = false;
   private List<String> saveOverride = null;

   public FriendManager() {
      this.read();
   }

   public boolean isFriend(String name) {
      return name.equals("KizuatoResult") || !this.paused && this.friendList.contains(name);
   }

   public boolean isFriend(PlayerEntity entity) {
      return this.isFriend(entity.getGameProfile().getName());
   }

   public void remove(String name) {
      this.friendList.remove(name);
   }

   public void add(String name) {
      if (!this.friendList.contains(name)) {
         this.friendList.add(name);
      }
   }

   public void friend(PlayerEntity entity) {
      this.friend(entity.getGameProfile().getName());
   }

   public void setPaused(boolean paused) {
      this.paused = paused;
   }

   public boolean isPaused() {
      return this.paused;
   }

   public void setSaveOverride(List<String> friends) {
      this.saveOverride = friends == null ? null : new ArrayList<>(friends);
   }

   public void clearSaveOverride() {
      this.saveOverride = null;
   }

   public void friend(String name) {
      if (this.friendList.contains(name)) {
         this.friendList.remove(name);
      } else {
         this.friendList.add(name);
      }
   }

   public void read() {
      try {
         File var1 = getFile("friends.txt");
         if (!var1.exists()) {
            return;
         }

         for (String var4 : IOUtils.readLines(new FileInputStream(var1), StandardCharsets.UTF_8)) {
            this.add(var4);
         }
      } catch (Exception var5) {
         var5.printStackTrace();
      }
   }

   public void save() {
      try {
         File var1 = getFile("friends.txt");
         PrintWriter var2 = new PrintWriter(new OutputStreamWriter(new FileOutputStream(var1), StandardCharsets.UTF_8));

         for (String var5 : this.saveOverride != null ? this.saveOverride : this.friendList) {
            var2.println(var5);
         }

         var2.close();
      } catch (Exception var6) {
         var6.printStackTrace();
         System.out.println("[CrucifiX beta] Failed to save friends");
      }
   }
}
