package ch.threema.app.emojis;

import java.util.LinkedList;

import ch.threema.app.preference.service.PreferenceService;

public class EmojiRecent {

    private final PreferenceService preferenceService;
    private static final int RECENT_SIZE_LIMIT = 100;
    private static LinkedList<String> recentList = new LinkedList<>(), recentListNew = new LinkedList<>();
    private static boolean modified = false;

    public EmojiRecent(PreferenceService preferenceService) {
        this.preferenceService = preferenceService;
        readFromPrefs();
    }

    public boolean add(String emojiSequence) {
        synchronized (recentListNew) {
            if (recentListNew.contains(emojiSequence)) {
                recentListNew.removeLastOccurrence(emojiSequence);
            }

            //resize list
            while (recentListNew.size() >= RECENT_SIZE_LIMIT) {
                recentListNew.removeLast();
            }

            recentListNew.addFirst(emojiSequence);

            modified = true;
        }
        return true;
    }

    public boolean remove(String emojiSequence) {
        synchronized (recentListNew) {
            if (recentListNew.contains(emojiSequence)) {
                recentListNew.remove(emojiSequence);
                modified = true;
                syncRecents();
                return true;
            }
        }
        return false;
    }

    public LinkedList<String> getRecentList() {
        return recentList;
    }

    public void saveToPrefs() {
        preferenceService.setRecentEmojis(recentListNew);
        syncRecents();
    }

    public void readFromPrefs() {
        if (preferenceService != null) {
            recentList = new LinkedList<>(preferenceService.getRecentEmojis());
            recentListNew = (LinkedList<String>) this.recentList.clone();
        }
    }

    public boolean syncRecents() {
        if (modified) {
            recentList = (LinkedList<String>) recentListNew.clone();
            modified = false;
            return true;
        }
        return false;
    }
}
