package performa.ws;

import java.util.*;
import oneit.appservices.config.ConfigMgr;
import oneit.appservices.ws.*;
import oneit.appservices.ws.services.BasicJSONService;
import oneit.business.content.*;
import oneit.business.content.jsp.*;
import oneit.objstore.*;
import oneit.security.SecUser;
import oneit.security.jsp.AssumeUserFP;
import oneit.servlets.jsp.BaseJSP;
import oneit.utils.*;
import oneit.utils.parsers.FieldException;
import oneit.utils.transform.MapTransform;
import oneit.utils.transform.param.PrefixCompoundTransform;
import org.json.*;
import performa.utils.*;

/**
 *
 * @author harsh
 */
public class AdminMenuJSONService extends BasicJSONService
{
    private static  final   PersonalisationHelper   HELPER  =   (PersonalisationHelper)ConfigMgr.getConfigObject("CONFIG.CONTENT", "StandardPersonalisationHelper");
    
    @Override
    public JSONObject serviceRequestSafe(JSONServiceRequest request) throws MultiException, FieldException, Exception
    {
        ObjectTransaction   objTran =   WSUtils.createTransaction(request);

        try
        {
            JSONObject  result      =   new JSONObject();
            SecUser     user        =   SecUser.getTXUser(objTran);
            SecUser     clientUser  =   Utils.checkAdminPortalAccess(user) ? user : null;

            result.put("userMenu", createUserMenu(request, objTran, clientUser));
            result.put("sidebarMenu", createSidebarMenu(request, objTran, clientUser));

            return result;
        }
        finally     // Clean up tranasaction in a finally
        {
            objTran.releaseResources();
        }
    }
    
    private JSONObject createUserMenu(JSONServiceRequest request, ObjectTransaction objTran, SecUser clientUser) throws JSONException
    {
        JSONObject  menu    =   new JSONObject();
        JSONArray   children=   new JSONArray();
        
        Article myDetailsArticle    =   WebUtils.getArticleByShortCut(objTran, WebUtils.MY_DETAILS);
        Article homeArticle         =   WebUtils.getArticleByShortCut(objTran, WebUtils.ADMIN_HOME);
        String  homeUrl             =   homeArticle.getLink(request.getRequest());
        String  signoutUrl          =   request.getRequest().getContextPath() + "/logout.jsp?nextURL=" + homeUrl;
        String  myDetailsLink       =   myDetailsArticle.getLink(request.getRequest(), CollectionUtils.mapEntry("cms.rm", "Page").toMap());
        
        children.put(createMenuItem("My Details", null, new String[] {Utils.ADMIN_IFRAME_PAGE_ROUTE, myDetailsLink}));
        children.put(createMenuItem("Sign Out", signoutUrl, null));
        
        if (request.getRequest().getSession().getAttribute (AssumeUserFP.UNASSUME_SEC_USER_ID) != null)
        {
            children.put(createMenuItem("Unassume", request.getRequest().getContextPath() + "/editor/index_unassume.jsp", null));
        }
        menu.put("label", Utils.getClientUserName(clientUser));
        menu.put("children", children);
        
        return menu;
    }
    
    private JSONObject createMenuItem(String label, String link, String[] routerLink) throws JSONException
    {
        JSONObject  item    =   new JSONObject();
        
        item.put("label", label);
        item.put("url", link);
        item.put("routerLink", JsonUtils.getJSONForm(routerLink));
        
        return item;
    }
    
    //Most of the code copied from CMSMenuTag.java
    private JSONObject createSidebarMenu(JSONServiceRequest request, ObjectTransaction objTran, SecUser clientUser) throws JSONException
    {
        JSONObject  menu    =   new JSONObject();
        JSONArray   children=   new JSONArray();
        
        Article             adminArticle=   WebUtils.getArticleByShortCut(objTran, WebUtils.ADMIN_PORTAL);
        NavigationBar       adminNavbar =   NavigationBarDF.loadSiteTree(objTran, adminArticle);
        NavigationBar       navbar      =   adminNavbar.getChildNavBarFor(adminArticle);
        
        MenuItemArbitrator  arbitrator  =   new MenuItemArbitrator("On Left Menu");
        NavigationBar[]     menus       =   navbar.getSubMenuItems(clientUser, arbitrator, new Integer(0));

        request.getRequest().setAttribute(BaseJSP.JSP_DATA, new HashMap());
        
        BaseJSP.addData(request.getRequest(), PersonalisationDF.HELPER, HELPER);
        
        if(menus != null)
        {
            for (int i=0; i < menus.length; i++)
            {
                Article         article         =   menus[i].getEntry();
                String          link            =   article.getLink(request.getRequest());
                ObjectTransform attribTransform =   CollectionUtils.getTransform(new ObjectTransform[] {new CMSMenuTag.AttributeTransform(request.getRequest(), menus[i]), StringUtils.TO_HTML_TRANSFORM});
                Object          disabled        =   new MenuItemDisableTransformFactory().createTransform(article, request.getRequest(), objTran).transform("disabled");
                Object          brakeLine       =   new BracklineSeparatorTransformFactory().createTransform(article, request.getRequest(), objTran).transform("true");
                Map             params          =   CollectionUtils.mapEntry("link", link)
                                                                .mapEntry("title", arbitrator.getTitle(request.getRequest(), menus[i], 0, menus[i].getSelected()))
                                                                .toMap();
                
                PrefixCompoundTransform paramTransform  =   new PrefixCompoundTransform();
                
                paramTransform.add("attrib", attribTransform);
                paramTransform.setDefault(new MapTransform(params));
                
                Object          routerLink      =   attribTransform.transform("Router Link");
                
                if(StringUtils.subBlanks(routerLink) == null)
                {
                    routerLink  =   new String[] {Utils.ADMIN_IFRAME_PAGE_ROUTE, link};
                }
                Map             menuItemMap     =   CollectionUtils.mapEntry("link", link)
                                                                .mapEntry("disabled", disabled)
                                                                .mapEntry("linkCSSClass", paramTransform.transform("attrib:Additional CSS Class"))
                                                                .mapEntry("iconCSSClass", paramTransform.transform("attrib:Menu Icon CSS"))
                                                                .mapEntry("title", paramTransform.transform("attrib:Menu Title|title"))
                                                                .mapEntry("brakeLine", brakeLine)
                                                                .mapEntry("routerLink", routerLink)
                                                                .toMap();
                
                children.put(JsonUtils.getJSONForm(menuItemMap));
            }
        }
        menu.put("children", children);
        
        return menu;
    }
}