package page.uk.co.mydisk;

import java.util.Arrays;

import org.wikiwebserver.core.WareHouse;
import org.wikiwebserver.handler.http.HTTPException;
import org.wikiwebserver.handler.http.interfaces.HTTPResponder;

import page.config.SiteTemplatedPage;
import page.tools.entity.NodeData;

import static org.wikiwebserver.html.HTMLHelper.*;

public class Index extends SiteTemplatedPage implements HTTPResponder {
	
	public static final long NODE_TASKS_FOR_REGISTRATION = 10;
	public static final long NODE_BYTES_FOR_REGISTRATION = 10 * 1024 * 1024;
	public static final long NODE_LAUNCHES_FOR_REGISTRATION = 3;

    public void generate() throws HTTPException {
        
        // For Google 
        appendToHead(meta("verify-v1", "h2M2EKCNoeF/LGQr8FXKRb40nvhxUstJuW8bx3OcwLc="));
        
        String[] keywords =  { 
        	"mydisk", "share hard disk online", "share files online", "hard disk sharing software",
        	"hard disk web share", "online disk", "disk sharing", "file sharing", "folder sharing",
        	"share folder online"
        };
        setKeywords(Arrays.asList(keywords));        
        
        setDescription("An easy-to-use solution for sharing files, folders and disks online.");
        
        addCSSLink("/templates/uk/co/mydisk/mydisk.css");
        
        String error = null;
        
        if (getFormData() != null) {
        	
            String action = getFormData().getFirst("action");
            String node = getFormData().getFirst("node");            
            if (action == null || action.equals("Access")) {
                if (node != null && node.length() > 0) {
                    NodeData nodeData = NodeData.getNodeDataByName(node);
                    if (nodeData != null) {
                        String nodeName = WareHouse.urlEncode(node);
                        String direct = getServiceAddress() + "/nodes/" + nodeName + "/";
                        throw new HTTPException(302, "Access Node", direct);
                    }
                    else error = "The node specified could not be found. Remember node names are case sensitive.";
                }
                else error = "Please enter the name of the node you wish to access.";
            }
            
            else if (action.equals("Share")) {
                String accept = getFormData().getFirst("accept");
                if (accept != null) {
                	
                	if (getUser() == null) {
	                	// Get heavy users to register (only works if MyDiskNode cookie shared with browser)
	                	String nodeId = getRequest().getHeaders().getRequestCookies().get("nodeID");
	                	if (nodeId != null) {              		
	                		NodeData nodeData = NodeData.getNodeDataById(nodeId);
	                		if (nodeData != null) {
	                			Number numTasks = (Number) nodeData.get("numTasksAssigned");
	                			Number bytesUploaded = (Number) nodeData.get("bytesUploaded");
	                			if (numTasks != null && bytesUploaded != null) {
	                				if (numTasks.longValue() > NODE_TASKS_FOR_REGISTRATION) {
	                					error = "You must sign-in to launch MyDiskNode. [T=" + numTasks + "]";
	                				}
		            				if (bytesUploaded.longValue() > NODE_BYTES_FOR_REGISTRATION) {
		            					error = "You must sign-in to launch MyDiskNode. [B=" + bytesUploaded + "]";
		            				}                			
	                			}
	                		}
	                	}
	                	
	                	// Get frequent users to register
	                	int launchCount = 0;
	                	String launchCountString = getRequest().getHeaders().getRequestCookies().get("mydiskLaunchCount");
	                	if (launchCountString != null) {
	                		launchCount = Integer.parseInt(launchCountString);
	                		launchCount++;
	                		if (launchCount > NODE_LAUNCHES_FOR_REGISTRATION) {
	                			error = "You must sign-in to launch MyDiskNode. [L=" + launchCount + "]";
	                		}
	                	}
            			getResponse().getHeaders().setResponseCookie("mydiskLaunchCount", String.valueOf(launchCount));		                	
                	}
                	
                	
                	if (error == null) {
	                    String jnlp = getServiceAddress() + WareHouse.getUrlPathForClass(JNLP.class);
	                    throw new HTTPException(302, "Launching MyDiskNode", jnlp);
                	}
                }
                else {
                	error = "You must accept the MyDisk terms of service to share files online.";
                }
            }           
        }
        
        setTitle("MyDisk.co.uk - Share your hard disk online");
        
        if (error != null) {
            append(h(1, "An error occured"));
            append(p(error, "class='error'"));
        }

        append(div("myDiskLogo", image("/templates/uk/co/mydisk/logo.gif", "MyDisk Logo")));
        
        if (getPageType() == PAGE_TYPE_DESKTOP) {
	        append(div("introduction", 
	               h(1, "What is MyDisk?") +
	               p("MyDisk is an easy-to-use solution for sharing files, folders and disks online.") +
	               p("By using a smart Java application, MyDisk routes Internet traffic to your computer making" +
	        		 " it easy to access files stored on your computer from anywhere in the world.") +
	        		 getGoogleAdsenseBlock("9958293172", 468, 60) +
	        	   p("Share documents, stream a music collection, share photos with friends or even host a" +
	        		 " personal web site. MyDisk makes sharing files on your computer easy. No complicated" +
	        		 " setup or installation required, no firewall rules or port forwarding  to worry about." +
	        		 " If you have Java and an Internet connection, you can share online.")));  
        }

        append(cleardiv());
        
        if (getPageType() == PAGE_TYPE_DESKTOP) {
            String termsUrl = "/templates/uk/co/mydisk/terms.html"; 
            append(div("shareDisk",
                    h(1, "Share a disk online") + form(
                    p("Start the " + strong("MyDiskNode") + " application to share a local file, folder or disk online.") +
                    p(label("accept", checkbox("accept", "true") + " I accept the " + 
                      a("#", "MyDisk terms of service",  "onclick=\"" + popupWindowJavaScript(termsUrl) + "\"") + ".")) +
                    p(submitbutton("action", "Share") + 
                    p("View advanced " + a(WareHouse.getUrlPathForClass(Options.class), "application options") + ".")
                    )))
            );
        }
        
        append(div("accessDisk",
                h(1, "Access a shared disk") + form(
                p("Connect to a remote node to access a shared file, folder or disk online.") +
                p("Node name: " + textfield("node")) + p(submitbutton("action", "Access")) +
                p("Connect to the " + a("/nodes/Example", "example node") + " or " + a("/nodes/", "browse all nodes") + ".")))
        );
        
        append(cleardiv());
        
        
        String oldMyDisk = "http://mydisk.hostyourself.net/";
        append(p("To share files online, " + a("http://www.java.com", "Java Runtime 6") + " or above is required."));
        append(p("Looking for the " + a(oldMyDisk, "old MyDisk sharing hub") + "?"));
        
        
        /*
        append(p("Please DO NOT post details of this new service to Digg, Slashdot or any other influential website." +
        		 " The service is still under development and is not ready for a surge of traffic."));
        */
        
        /*
        String counterUrl = WareHouse.getUrlPathForClass(page.image.Counter.class) + "?size=11&amp;name=MyDisk";
        append(image(counterUrl, "Page hits", "id='counterImage'") + cleardiv());
        */     
    }
    
    private String popupWindowJavaScript(String url) {
    	return "window.open('" + url + "','terms','width=400,height=400,scrollbars=yes');";
    }
}
