package ru.yandex.webmaster3.storage.notifications;

import ru.yandex.webmaster3.core.text.templates.TextTemplate;

import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;

/**
 * @author avhaliullin
 */
public class NotificationTemplate extends TextTemplate<NotificationPlaceholder> {
    private NotificationTemplate(List<Entry<NotificationPlaceholder>> entries, int textLength, Map<NotificationPlaceholder, Integer> phsCount) {
        super(entries, textLength, phsCount);
    }

    public static NotificationTemplate parseTemplate(String templateString) {
        int i = 0;
        List<Entry<NotificationPlaceholder>> entries = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        boolean insidePlaceholder = false;

        int textLength = 0;
        Map<NotificationPlaceholder, Integer> phSCount = new EnumMap<>(NotificationPlaceholder.class);

        while (i < templateString.length()) {
            char c = templateString.charAt(i);
            if (c == '@' && (i + 1) < templateString.length()) {
                char nextC = templateString.charAt(i + 1);
                if (nextC == '@') {
                    if (insidePlaceholder) {
                        String phName = sb.toString();
                        NotificationPlaceholder placeholder = NotificationPlaceholder.R.valueOfOrNull(phName);

                        // Игнорируем неправильные плейсхолдеры
                        if (placeholder == null) {
                            sb.insert(0, "@@");
                            sb.append("@@");
                            insidePlaceholder = false;
                            i += 2;
                            continue;
                        }
                        entries.add(new PlaceholderEntry<>(placeholder));
                        Integer currentPHsCount = phSCount.getOrDefault(placeholder, 0);
                        phSCount.put(placeholder, currentPHsCount + 1);
                    } else {
                        if (sb.length() > 0) {
                            entries.add(new TextEntry<>(sb.toString()));
                            textLength += sb.length();
                        }
                    }
                    insidePlaceholder = !insidePlaceholder;
                    i += 2;
                    sb.setLength(0);
                    continue;
                }
            }

            sb.append(c);
            i++;
        }
        if (insidePlaceholder) {
            sb.insert(0, "@@");

        }
        if (sb.length() > 0) {
            entries.add(new TextEntry<>(sb.toString()));
            textLength += sb.length();
        }

        return new NotificationTemplate(entries, textLength, phSCount);
    }
}
