package jesse.keeblarcraft.MailSystem;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import jesse.keeblarcraft.ConfigMgr.ConfigManager;

public class MailMgr {
    ConfigManager config = new ConfigManager();
    MailConfigClass mailConfig;
    String CONFIG_FILE = "mail/player_mail.json";

    private static MailMgr static_inst;
    public static MailMgr GetInstance() {
        if (static_inst == null) {
            static_inst = new MailMgr();
        }
        return static_inst;
    }

    private class MailConfigClass {
        private HashMap<String, ArrayList<String>> mailList = new HashMap<String, ArrayList<String>>();
    }

    public MailMgr() {
        System.out.println("Mail manager called");
        Boolean existingFile = false;
        try {
            mailConfig = config.GetJsonObjectFromFile(CONFIG_FILE, MailConfigClass.class);
            existingFile = true;
        } catch (Exception e) {
            System.out.println("Mail config could not correctly parse json file or it did not exist");
        }

        if (!existingFile) {
            try {
                config.CreateFile(CONFIG_FILE);
            } catch (Exception e) {
                System.out.println("Failed to correctly make or parse mail config file");
            }
        }
    }

    public void SendMail(String playerUuid, String mail) {
        if (mailConfig != null) {
            if (mailConfig.mailList.containsKey(playerUuid)) {
                mailConfig.mailList.get(playerUuid).add(mail);
            } else {
                mailConfig.mailList.put(playerUuid, new ArrayList<>(Arrays.asList(mail)));
            }
        } else {
            System.out.println("Mail config is null. Cannot send");
        }
    }

    public List<String> GetMail(String playerUuid) {
        List<String> mail = null;
        if (mailConfig.mailList.containsKey(playerUuid)) {
            mail = mailConfig.mailList.get(playerUuid);
        }
        return mail;
    }

    public void ClearMail(String playerUuid) {
        if (mailConfig != null && mailConfig.mailList.containsKey(playerUuid)) {
            mailConfig.mailList.remove(playerUuid);
        }
    }

    public void FlashConfig() {
        if (mailConfig != null) {
            try {
                config.WriteToJsonFile(CONFIG_FILE, mailConfig);
            } catch (Exception e) {
                System.out.println("Could not flash mail config");
            }
        }
    }
}
