package page.com.googleoids;

import java.util.Map;
import java.util.TreeSet;

import org.wikiwebserver.core.Privilege;
import org.wikiwebserver.core.WareHouse;
import org.wikiwebserver.handler.http.interfaces.*;
import org.wikiwebserver.util.HumanNumber;
import org.wikiwebserver.util.comparator.DescendingEntryValueComparator;

import page.config.SiteTemplatedPage;
import page.tools.entity.Browser;
import page.tools.entity.User;


import static org.wikiwebserver.html.HTMLHelper.*;


public class HighScores extends SiteTemplatedPage implements HTTPResponder {
    
    public void generate() {
        addCSSLink("/templates/com/googleoids/googleoids.css");        

        Browser b = getBrowser();  
        User u = getUser();
        
        Long lastScore = (Long) b.get("lastScore", "Googleoids");
        Long highScore = (Long) b.get("highScore", "Googleoids");
        Long highScoreTime = (Long) b.get("highScoreTime", "Googleoids");
        Integer highLevel = (Integer) b.get("highLevel", "Googleoids");
        String result = (String) b.get("result", "Googleoids");               
        
        if (getFormData() != null) {
            String playerName = getFormData().getFirst("playername");
            if (b != null) {
                if (playerName != null && playerName.length() > 0) {
                    playerName = WareHouse.escapeHTMLEntities(playerName);
                    if (playerName.length() > 32) {
                        playerName = playerName.substring(0, 32);
                    }
                    b.put("playerName", playerName, "Googleoids");
                    getPageData().put(b.getId(), highScore);
                }
                if (u != null && u.getPrivilege().isAbove(Privilege.MODERATOR)) { 
                    String browserid = getFormData().getFirst("delID");
                    if (browserid != null) {
                        Browser.getBrowserById(browserid).put("highScore", new Long(0), "Googleoids", "HighScores");
                        getPageData().remove(b.getId());
                    }
                }
            }
        }
        
        String playerName = (String) b.get("googleoidsPlayerName");
        if (playerName == null) playerName = "";
        
        setTitle("High Scores - Googleoids");
               
        append(h(1,"Your Results"));  
        
        if (highScore != null && lastScore != null && highLevel != null) {
            append(p(result)); 
            
            if (lastScore.longValue() < highScore.longValue()) {
                append(h(2, "Your Score")); 
                append(div("highscore", WareHouse.formatNumber(lastScore))); 
            }
            
            append("<div class='rightside'><h2>Level</h2>" +
                    "<div id='highscore'>" + WareHouse.formatNumber(highLevel) + "</div></div>");                       
                   
            append("<h2>Your Highest Score</h2>" +
                    "<div id='highscore'>" +  WareHouse.formatNumber(highScore) + "</div>");
             
            append(p("(" + HumanNumber.format(highScore) + ")"));   
            
            if (highScoreTime != null) {
                append(p("Scored on " + WareHouse.formatStandardDate(highScoreTime)));   
            }
            
            append(h(2, "Player Name") +
                   form(textfield("playername", playerName) +
                        submitbutton("action", "Add to highscore table")));
                     
        }
        else {
            append(p("Failed to find your results. Either you have not played or there" +
            	   " is something wrong with your cookies.")); 
        }
        
        append(h(1, "Googleoids High Scores"));
        
        append(getHighScoreTable(500));
        
        String url = WareHouse.getUrlPathForClass(page.com.googleoids.Index.class);
        append(h(1, "Custom start search") +
                "<form method='GET' action='" + url + "'>" +
                    textfield("q", "Banana") +
                    submitbutton("action", "Play Googleoids") +
                "</form>");        
    }
    
    
    private String getHighScoreTable(int limit) {
        
        StringBuilder body = new StringBuilder();
        Browser current = getBrowser();
        
        TreeSet<Map.Entry<String, Object>> sortedSet 
            = new TreeSet<Map.Entry<String, Object>>(
                    new DescendingEntryValueComparator<String, Object>());

        if (getPageData() != null) {
            for (Map.Entry<String, Object> entry : getPageData().entrySet()) {
                sortedSet.add(entry);
            }
        }
        
        body.append("<table>"); 
        body.append("<th>Player name</th>"); 
        body.append("<th>Highest Score</th>"); 
        body.append("<th>Level</th>"); 
        body.append("<th>High Score Time</th>");     
        
        User u = getUser();
        if (u != null && u.getPrivilege().isAbove(Privilege.MODERATOR)) { 
            body.append("<th>Monitor</th>"); 
        }
        
        int c=0;
        for (Map.Entry<String, Object> entry: sortedSet) {
            Browser b = Browser.getBrowserById(entry.getKey());
            
            if (b != null) {
                Long highScore = (Long) b.get("highScore", "Googleoids");
                Long highScoreTime = (Long) b.get("highScoreTime", "Googleoids");
                Integer highLevel = (Integer) b.get("highLevel", "Googleoids");
                String playername = (String) b.get("playerName", "Googleoids");
                
                if (playername != null && playername.length() > 0) { 
                    
                    String cls = b.equals(current) ? "current" : "normal";
                    body.append("<tr>");
                    body.append("<td class='" + cls + "'>" + playername + "</td>"); 
                    body.append("<td class='" + cls + "'>" + WareHouse.formatNumber(highScore) + "</td>"); 
                    body.append("<td class='" + cls + "'>" + highLevel + "</td>"); 
                    body.append("<td class='" + cls + "'>" + WareHouse.formatStandardDate(highScoreTime) + "</td>");
                    if (u != null && u.getPrivilege().isAbove(Privilege.MODERATOR)) { 
                        String trace = WareHouse.getUrlPathForClass(page.tools.stats.BrowserInfo.class)
                                     + "?browserID=" + b.getId();
                        String del = "?delID=" + b.getId();
                        body.append("<td>[ <a href='" + trace + "'>Trace</a> | <a href='" + del + "'>Delete</a> ]</td>"); 
                    }                
                    body.append("</tr>"); 
                }
        
                if (c++ > limit) break;
            }
        } 
        
        body.append("</table>"); 

        
        return body.toString();
    }        
}


