package page.config;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Map;

import org.wikiwebserver.core.WareHouse;
import org.wikiwebserver.handler.http.HTTPException;
import org.wikiwebserver.handler.http.HTTPHandler;
import org.wikiwebserver.html.HTMLHelper;
import org.wikiwebserver.html.TemplatedPage;

import static org.wikiwebserver.html.HTMLHelper.*;

import page.tools.admin.JQueryQuickSignIn;
import page.tools.entity.Browser;
import page.tools.entity.NodeData;
import page.tools.entity.User;
import page.tools.html.NavigationMenu;

public class SiteTemplatedPage extends TemplatedPage {
    
    private long startResponseNanoTime;    
    private String[][] navigationItems = null;    

    public SiteTemplatedPage() {
        startResponseNanoTime = System.nanoTime();
        // default title
        setTitle("Untitled WikiWebServer Page");      
    }
    
    public void init(HTTPHandler conn) throws HTTPException {
        super.init(conn);
        
        setSiteTitle("WikiWebServer<span>.org</span>");
        setSiteSlogan("The dynamic, rewritable Java web server <sup>BETA</sup>");        
        
        String host = getRequest().getHeaders().getFirst("Host");
        if (host != null) {
            
            // Strip off port
            int portIdx = host.indexOf(':');
            if (portIdx != -1) {
                host = host.substring(0, portIdx);
            }            
    
            if (host.startsWith("m.wikiwebserver.org")) {
                setNavigationItems(new String[][] {
                        { "Home",           "/" },
                        { "Mobiliser",      "/mobilise/" },        
                        { "Examples",       "/examples/" },
                        { "Users",          "/user/" },
                        { "Files",          "/files/" },
                        { "Changes",        "/changes/" },        
                        { "Status",         "/status/" }
                });              
            }
            
            if (host.endsWith("jfilerecovery.com")) {
                setSiteTitle("JFileRecovery<span>.com</span>");
                setSiteSlogan("Copy files from damaged hard drives, CDs, DVDs and Flash media.");             
                setNavigationItems(new String[][] {
                        { "Information",  WareHouse.getUrlPathForClass(page.com.jfilerecovery.Index.class) },
                        { "CRC Errors",   WareHouse.getUrlPathForClass(page.com.jfilerecovery.CRCErrors.class) },
                        { "User Reviews", WareHouse.getUrlPathForClass(page.com.jfilerecovery.UserReviews.class) },
                        { "Download",     WareHouse.getUrlPathForClass(page.com.jfilerecovery.Download.class) },   
                });
            } 
            
            if (host.endsWith("googleoids.com")) {
                setSiteTitle("Googleoids<span>.com</span>");
                setSiteSlogan("The crazy cross between searching and scrabble! <sup>BETA</sup>");          
                setNavigationItems(new String[][] {
                        { "How to Play",     WareHouse.getUrlPathForClass(page.com.googleoids.Instructions.class) },
                        { "Play Googleoids", WareHouse.getUrlPathForClass(page.com.googleoids.Index.class) },
                        { "High Scores",     WareHouse.getUrlPathForClass(page.com.googleoids.HighScores.class) },
                });
            } 
            
            if (host.endsWith("jrsstray.com")) {
                setSiteTitle("JRSSTray<span>.com</span>");
                setSiteSlogan("Display the latest RSS news, live in the tray.");       
                setNavigationItems(new String[][] {
                        { "Information",  WareHouse.getUrlPathForClass(page.com.jrsstray.Index.class) },
                        { "Download",     WareHouse.getUrlPathForClass(page.com.jrsstray.Download.class) },   
                });
            }   
            
            if (host.endsWith("jfirewalltest.com")) {
                setSiteTitle("JFirewallTest<span>.com</span>");
                setSiteSlogan("Scan network ports for holes in your firewall.");       
                setNavigationItems(new String[][] {
                        { "Information",   WareHouse.getUrlPathForClass(page.com.jfirewalltest.Index.class) },
                        { "Launch", WareHouse.getUrlPathForClass(page.com.jfirewalltest.Launch.class) },                
                        { "Results", WareHouse.getUrlPathForClass(page.com.jfirewalltest.PortScanner.class) },  
                });
            }              
            
            if (host.endsWith("mydisk.co.uk")) {
                setSiteTitle("MyDisk<span>.co.uk</span>");
                setSiteSlogan("Share your hard disk online <sup>BETA 3.0</sup>");               
                setNavigationItems(new String[][] {
                        { "Home",           "/" },
                        { "FAQ",            WareHouse.getUrlPathForClass(page.uk.co.mydisk.FAQ.class) },
                        { "Nodes",          "/nodes/" },
                        { "Users",          "/user/" },                        
                        // { "Upgrades",       WareHouse.getUrlPathForClass(page.uk.co.mydisk.Upgrade.class) },
                });
            }  
            
            if (host.endsWith("michaelgardiner.info")) {
                setSiteTitle("MichaelGardiner<span>.info</span>");
                setSiteSlogan("A personal information page <sup>BETA</sup>");            
                setNavigationItems(new String[][] {
                        { "Profile", WareHouse.getUrlPathForClass(page.info.michaelgardiner.Index.class) },
                        { "Portfolio", WareHouse.getUrlPathForClass(page.info.michaelgardiner.Portfolio.class) },                        
                });
            }        
        }
        
        
        // Default navigation items if not set
        if (navigationItems == null) {
            navigationItems = new String[][] {
                    { "Home",           "/" },
                    { "Examples",       "/examples/" },
                    { "Users",          "/user/" },
                    { "Nodes",          "/nodes/" },                    
                    { "Files",          "/files/" },
            };
        }        
    }
    
    protected void addTemplateModifications(Map<String, String> changes) throws IOException {
        changes.put("<!-- QUICK_SIGN_IN_JAVASCRIPT -->", getSignInJavaScript());
        changes.put("<!-- NAVIGATION_MENU -->", getNavigationMenu());
        changes.put("<!-- PAGE_FORMATS -->", getPageFormats());  
        changes.put("<!-- COPYRIGHT -->", getCopyRight());        
        changes.put("<!-- BROWSER_BYTES -->", WareHouse.formatNumber(getBrowserBytes()));       
        super.addTemplateModifications(changes);
    }   
    
    protected String getPageFormats() throws IOException {
        
        StringBuilder formatLinks = new StringBuilder();
        String host = getHandler().getRequest().getHeaders().getFirst("Host");
        if (host != null && !Character.isDigit(host.charAt(0))) {
            formatLinks.append("[ ");
            String[] protocols = { "https", "http", "http" };
            String[] prefixes = { "secure.", "m.", "www." };
            String[] formats = { "secure", "mobile", "normal" };
            // Strip prefixes
            for (int i=0; i<prefixes.length; i++) {
                if (prefixes[i] != null && host.startsWith(prefixes[i])) {
                    host = host.substring(prefixes[i].length());
                }
            }
            // Generate page type links
            for (int i=0; i<formats.length; i++) {
                String url = protocols[i] + "://";
                if (prefixes[i] != null) url += prefixes[i];
                url += host + getHandler().getRequest().getUri();
                formatLinks.append(a(url, formats[i]));
                if (i < formats.length-1) {
                    formatLinks.append(" | ");
                }
            }
            formatLinks.append(" ]");
        }
        
        return formatLinks.toString();
    }
    
    protected String getCopyRight() throws IOException {
        
        long genTime = System.nanoTime() - startResponseNanoTime;
        DecimalFormat rounder = new DecimalFormat("0.000");
        
        String ms = rounder.format(((double)genTime) / 1000000);
        String s = rounder.format(((double)genTime) / 1000000000);
        
        String year = WareHouse.formatDate(System.currentTimeMillis(), "yyyy");
        

        return "Web site powered by " + 
               a("http://www.wikiwebserver.org/", "WikiWebServer") +
               ". &copy; 2007-" + year + " " +
               a("http://www.jads.co.uk/", "JADS Limited") + "." +
               " [<font title='Page generated in " + ms + " ms.'>" + s + "s</font>]";
    } 
    
    public String getSignInJavaScript() {
        
        if (getPageType() == TemplatedPage.PAGE_TYPE_DESKTOP) {
            String quickSignIn = WareHouse.getUrlPathForClass(JQueryQuickSignIn.class);
            return
                "$(document).ready(function(){" + LF + 
                "  $('#quick-signin').fadeTo(10, 0);" + LF + 
                "  $('#quick-signin').load('" + quickSignIn + "', '', function(){" + LF + 
                "    $('#quick-signin').fadeTo(200, 1);" + LF + 
                "  });" + LF + 
                "});";     
        }    
        return "";
    }
    
    public void setNavigationItems(String[][] items) {
        this.navigationItems = items;
    }    
    
    protected String getNavigationMenu() {
        if (getPageType() == PAGE_TYPE_MOBILE) {
            return ("<a href='/nav/'>Navigation menu</a>");
        }

        NavigationMenu nav = new NavigationMenu();
        nav.setCurrentUrl(getRequest().getUrl());
        nav.setNavigationItems(navigationItems);

        return nav.getBody();
    }    

    public User getUser() {
        return User.getUser(getRequest());
    }
    
    
    public static File getUserDir(User user) {
        if (user == null) return null;
        
        File file = new File(WareHouse.USER_ROOT + "u" + user.getId());
        return file;
    }   
    
    public static String emailImage(User user) {
        return emailImage(user, 12);
    }
    
    public static String avatarImage(User user) {
        return avatarImage(user, null);
    }
    
    public static String avatarImage(User user, String additional) {
        if (user == null) return "";
        String src = WareHouse.getUrlPathForClass(page.image.UserAvatar.class) + 
                     "?userID=" + user.getId();
        if (additional == null) {
            additional = "class='avatar'";
        }
        return HTMLHelper.image(src, "Avatar", additional);  
    }
    
    public static String nodeImage(NodeData nodeData) {
        return nodeImage(nodeData, null);
    }    
    
    public static String nodeImage(NodeData nodeData, String additional) {
        if (nodeData == null) return "";
        String src = WareHouse.getUrlPathForClass(page.image.NodeAvatar.class) + 
                     "?nodeID=" + nodeData.getId();
        if (additional == null) {
            additional = "class='avatar'";
        }
        return HTMLHelper.image(src, "Avatar", additional);  
    }    
    
    public static String emailImage(User user, int size) {
        if (user == null) return "";
        boolean showName = user.get("showname") != null;
        String src = WareHouse.getUrlPathForClass(page.image.Email.class);        
        if (showName) {
            String fullName = (String) user.get("fullname");
            return HTMLHelper.image(src + "?size=" + size + "&email=" + fullName, 
                    "Email address hidden", "class='emailImage' border='0'");   
        } else {
            String email = user.getEmail();
            email = email.replace("@", "-at-");
            email = email.replace(".", "-dot-");   
            return HTMLHelper.image(src + "?size=" + size + "&email=" + email, 
                         "bot-proof-email", "class='emailImage' border='0'");    
        }
    }    

    public Browser getBrowser() {
        return Browser.getBrowser(this.getHandler());
    }    
    
    protected long getBrowserBytes() {
        Browser b = getBrowser();
        if (b != null) {
            Number count = (Number) b.get("bytesDownloaded");
            if (count != null) {
                return count.longValue();
            }
        }
        return 0;
    }    
   
    
    public String cacheKeyBasedOnUser() {
        if (getUser() == null) return "";
        return "u" + getUser().getId();
    }    
    
    public String cacheKeyBasedOnBrowser() {
        if (getBrowser() == null) return "";
        return "b" + getBrowser().getId();
    }    

    protected void generate() throws HTTPException {
        // TODO Auto-generated method stub
        
    }    
}

