package se.koc.trader.endpoint;

import se.koc.trader.TraderContext;
import se.koc.trader.api.TraderApiEndpoint;
import zutil.io.file.FileUtil;
import zutil.log.LogUtil;
import zutil.parser.DataNode;
import zutil.parser.Templator;
import zutil.ui.UserMessageManager;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

public class AlertEndpoint extends TraderApiEndpoint {
    private static final Logger logger = LogUtil.getLogger();
    private static final String TEMPLATE = TraderContext.RESOURCE_WEB_ROOT + "/main_alerts.tmpl";
    private static final String API_PATH = "/api/alert";

    private static AlertEndpoint instance;


    private AlertEndpoint() {
        super(API_PATH);
    }


    public String getUrl() {
        return "/" + API_PATH;
    }


    public Templator generateAlerts() {
        try {
            List<UserMessageManager.UserMessage> messages = TraderContext.getMessageManager().getMessages();
            TraderContext.getMessageManager().decreaseTTL();

            Templator tmpl = new Templator(FileUtil.find(TEMPLATE));
            tmpl.set("serviceUrl", getUrl());
            tmpl.set("alerts", messages);
            return tmpl;
        } catch (IOException e) {
            logger.log(Level.SEVERE, null, e);
        }
        return null;
    }

    @Override
    protected DataNode jsonRespond(Map<String, Object> session, Map<String, String> cookie, Map<String, String> request) throws Exception {
        if (request.containsKey("action")) {
            if (request.get("action").equals("dismiss")) {
                // parse alert id
                int id = Integer.parseInt(request.get("id"));
                //  Find alert
                UserMessageManager.UserMessage msg = TraderContext.getMessageManager().get(id);
                if (msg != null)
                    msg.dismiss();
            }
        }

        return new DataNode(DataNode.DataType.Map);
    }


    public static AlertEndpoint getInstance() {
        if (instance == null)
            instance = new AlertEndpoint();
        return instance;
    }
}
