/*
 * Copyright (c) 2015 Ziver
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package wa.server;

import wa.server.page.ServicePage;
import wa.server.page.StatusPage;
import wa.server.page.WAPage;
import wa.server.page.struct.WANavigation;
import zutil.io.file.FileUtil;
import zutil.log.LogUtil;
import zutil.net.http.HttpHeader;
import zutil.net.http.HttpPage;
import zutil.net.http.HttpPrintStream;
import zutil.parser.DataNode;
import zutil.parser.Templator;
import zutil.parser.json.JSONWriter;
import zutil.plugin.PluginManager;

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

/**
 * Created by Ziver on 2015-04-02.
 */
public class WAAbstractPage implements HttpPage{
    private static final Logger log = LogUtil.getLogger();
    private static final String TMPL_FILE = "WebContent/page/index.tmpl";

    private List<WAPage> pages;
    private Templator tmpl;

    public WAAbstractPage(PluginManager pluginManager) {
        try {
            pages = Arrays.asList(new WAPage[] {
                new StatusPage(pluginManager),
                new ServicePage(pluginManager)
            });

            tmpl = new Templator(FileUtil.find(TMPL_FILE));
        } catch(IOException e){
            log.log(Level.SEVERE, null, e);
            tmpl = new Templator(e.getMessage());
        }
    }


    @Override
    public final synchronized void respond(HttpPrintStream out,
                        HttpHeader client_info,
                        Map<String, Object> session,
                        Map<String, String> cookie,
                        Map<String, String> request) throws IOException {
        WAContext context = new WAContext(request);
        List<WANavigation> breadcrumb = context.getBreadcrumb();
        WAPage page = null;
        if(breadcrumb.size() > 0){
            int i = pages.indexOf(breadcrumb.get(0).getResource());
            if(i >= 0)
                page = pages.get(i);
        }

        if(("application/json").equals(client_info.getHeader("ContentType")) ||
                request.containsKey("json")){
            DataNode node = null;
            if(page != null)
                node = page.jsonResponse(context, client_info, session, cookie, request);
            if(node != null) {
                out.setHeader("Content-Type", "application/json");
                JSONWriter writer = new JSONWriter(out);
                writer.write(node);
                writer.close();
            }
        }
        else {
            tmpl.clear();

            tmpl.set("title", "WebAdmin");
            tmpl.set("top-nav", context.getNavigation());
            tmpl.set("side-nav-show", true);
            if(breadcrumb.size() >= 1)
                tmpl.set("side-nav", breadcrumb.get(0).getSubNavs());
            tmpl.set("breadcrumb", breadcrumb);
            tmpl.set("alerts", context.getAlerts());
            //tmpl.set("footer", null);

            Templator content = null;
            if(page != null)
                content = page.htmlResponse(context, client_info, session, cookie, request);
            if(content != null) {
                if(!breadcrumb.isEmpty())
                    content.set("nav", breadcrumb.get(breadcrumb.size() - 1));
                tmpl.set("content", content);
            }

            out.print(tmpl.compile());
        }
    }

}
