/*
 * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved.
 *
 * The contents of this file are subject to the CCM Public
 * License (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the
 * License at http://www.redhat.com/licenses/ccmpl.html.
 *
 * Software distributed under the License is distributed on an
 * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
 * or implied. See the License for the specific language
 * governing rights and limitations under the License.
 *
 */
package com.arsdigita.cms.ui;


import com.arsdigita.bebop.Component;
import com.arsdigita.bebop.Label;
import com.arsdigita.bebop.Link;
import com.arsdigita.bebop.List;
import com.arsdigita.bebop.Page;
import com.arsdigita.bebop.FormSection;
import com.arsdigita.bebop.PageState;
import com.arsdigita.bebop.list.ListCellRenderer;
import com.arsdigita.bebop.parameters.StringParameter;
import com.arsdigita.cms.ContentItem;
import com.arsdigita.cms.dispatcher.Utilities;
import com.arsdigita.persistence.OID;
import com.arsdigita.xml.Element;
import com.arsdigita.web.ParameterMap;
import com.arsdigita.web.URL;

import com.arsdigita.search.Search;
import com.arsdigita.search.Document;
import com.arsdigita.search.ui.QueryGenerator;
import com.arsdigita.search.ui.ResultsPane;

import java.math.BigDecimal;
import javax.servlet.http.HttpServletRequest;

/**
 * An extension of {@link ItemSearch} for use in a popup
 * search window. The display of results is altered so that
 * selecting a result closes the window & passes the id of
 * the selected item back to the opener.
 *
 * @author Stanislav Freidin (sfreidin@arsdigita.com)
 * @version $Id: //cms/dev/src/com/arsdigita/cms/ui/ItemSearchPopup.java#10 $
 */
public class ItemSearchPopup extends ItemSearch {


    private static final org.apache.log4j.Logger s_log = 
        org.apache.log4j.Logger.getLogger(ItemSearchPopup.class);

    public static final String WIDGET_PARAM = "widget";
    public static final String URL_PARAM = "useURL";

    /**
     * Construct a new <code>ItemSearchPopup</code> component
     *
     * @param context the context for the retrieved items. Should be
     *   {@link ContentItem#DRAFT} or {@link ContentItem#LIVE}
     */
    public ItemSearchPopup(String context) {
        super(context);
    }

    // Hide results by default
    public void register(Page p) {
        super.register(p);
        p.addGlobalStateParam(new StringParameter(WIDGET_PARAM));
        p.addGlobalStateParam(new StringParameter(URL_PARAM));
    }

    protected ItemSearchSection createSearchSection(String context) {
        return new ItemSearchSectionPopup(context);
    }

    private static class ItemSearchSectionPopup extends ItemSearchSection {
        
        public ItemSearchSectionPopup(String context) {
            super(context);
        }
        
        protected Component createResultsPane(QueryGenerator generator) {
            return new PopupResultsPane(generator);
        }
    }

    public static String getLiveItemURL(HttpServletRequest request, OID oid) {
        // redirect doesn't use /ccm prefix for some reason, so just returning the raw string.
        //ParameterMap map = new ParameterMap();
        //map.setParameter("oid", oid.toString());
        //return URL.there(request, "/redirect/", map).toString();
        // Always link directly to the live version.
        return "/redirect/?oid="+oid.toString() + "&context=live";
    }

    private static class PopupResultsPane extends ResultsPane {
        public PopupResultsPane(QueryGenerator generator) {
            super(generator);
        }

        protected Element generateDocumentXML(PageState state,
                                              Document doc) {
            Element element = super.generateDocumentXML(state, doc);
            
            element.addAttribute("class", "jsButton");

            String widget = (String) state.getValue(
                new StringParameter(WIDGET_PARAM));
            
            boolean useURL = "true".equals(
                state.getValue(new StringParameter(URL_PARAM)));

            String fillString = useURL ? 
                getLiveItemURL(state.getRequest(), doc.getOID()) :
                doc.getOID().get("id").toString() + 
                " (" + doc.getTitle() + ")";
            
            Element jsLabel = Search.newElement("jsAction");
            jsLabel.addAttribute("name", "fillItem" + 
                                 doc.getOID().get("id") + "()");
            jsLabel.setText(generateJSLabel((BigDecimal)doc.getOID().get("id"), 
                                            widget,  fillString));
            element.addContent(jsLabel);

            return element;
        }

        private String generateJSLabel(BigDecimal id, String widget, String fill) {
            return " <script language=javascript> " +
                " <!-- \n" +
                " function fillItem" +
                id +
                "() { \n" +
                " window.opener.document." +
                widget + ".value=\"" + fill + "\";\n" +
                " self.close(); \n" +
                " return false; \n" +
                " } \n" +
                " --> \n" +
                " </script> ";
        }
    }
}
