/*
 * Copyright (C) 2010 Teleal GmbH, Switzerland
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.teleal.cling.support.contentdirectory;

import org.teleal.cling.controlpoint.ActionCallback;
import org.teleal.cling.model.action.ActionArgumentValue;
import org.teleal.cling.model.action.ActionException;
import org.teleal.cling.model.action.ActionInvocation;
import org.teleal.cling.model.message.UpnpResponse;
import org.teleal.cling.model.meta.Service;
import org.teleal.cling.model.types.ErrorCode;
import org.teleal.cling.model.types.UnsignedIntegerFourBytes;
import org.teleal.cling.support.contentdirectory.descriptor.DIDLParser;
import org.teleal.cling.support.contentdirectory.descriptor.didl.DIDLLite;

import java.util.logging.Logger;

/**
 * Invokes a "Browse" action and calls back with a <tt>DIDLLite</tt> instance ready to use.
 *
 * @author Christian Bauer
 */
public abstract class BrowseActionCallback extends ActionCallback {

    public enum Status {
        LOADING("Loading..."),
        OK("OK");

        private String defaultMessage;

        Status(String defaultMessage) {
            this.defaultMessage = defaultMessage;
        }

        public String getDefaultMessage() {
            return defaultMessage;
        }
    }

    private static Logger log = Logger.getLogger(BrowseActionCallback.class.getName());

    public BrowseActionCallback(Service service, String containerId, boolean directChildren) {
        this(service, containerId, directChildren, "*", 0, null, null);
    }

    public BrowseActionCallback(Service service, String containerId, boolean directChildren,
                                String filter, long firstResult, Long maxResults, String orderBy) {

        super(new ActionInvocation(service.getAction("Browse")));

        log.fine("Creating browse action for container ID: " + containerId);

        getActionInvocation().setInput("ObjectID", containerId);
        getActionInvocation().setInput("BrowseFlag", directChildren ? "BrowseDirectChildren" : "BrowseMetadata");
        getActionInvocation().setInput("Filter", filter);
        getActionInvocation().setInput("StartingIndex", new UnsignedIntegerFourBytes(firstResult));
        getActionInvocation().setInput("RequestedCount",
                new UnsignedIntegerFourBytes(maxResults == null ? getDefaultMaxResults() : maxResults)
        );
        getActionInvocation().setInput("SortCriteria", orderBy);
    }

    @Override
    public void run() {
        updateStatus(Status.LOADING);
        super.run();
    }

    public void success(ActionInvocation invocation) {
        log.fine("Successful browse action, reading output argument values");

        String didlXML = invocation.getOutput("Result").getValue().toString();
        Long numberReturned = ((UnsignedIntegerFourBytes) invocation.getOutput("NumberReturned").getValue()).getValue();
        Long totalMatches = ((UnsignedIntegerFourBytes) invocation.getOutput("TotalMatches").getValue()).getValue();

        if (numberReturned > 0 &&  didlXML.length() > 0) {
            try {
                receivedRaw(invocation, didlXML);
/*
                if (log.isLoggable(Level.FINER)) {
                    log.finer("-------------------------------------------------------------------------------------");
                    log.finer("\n" + XML.pretty(didlXML));
                    log.finer("-------------------------------------------------------------------------------------");
                }
*/

                DIDLParser didlParser = new DIDLParser(false);
                DIDLLite didl = didlParser.read(didlXML);
                received(invocation, didl);
                updateStatus(Status.OK);

                // TODO: Not useful and not pretty
                if (totalMatches != null && totalMatches > getDefaultMaxResults()) {
                    log.warning("Total matches of browse result is larger than hard limit of " + getDefaultMaxResults());
                }

            } catch (Exception ex) {
                invocation.setFailure(
                        new ActionException(ErrorCode.ACTION_FAILED, "Can't parse DIDL XML response: " + ex, ex)
                );
                failure(invocation, null);
            }
        } else {
            receivedRaw(invocation, null);
            received(invocation, null);
            updateStatus(Status.OK);
        }
    }

    public void failure(ActionInvocation invocation, UpnpResponse operation) {
        failure(createDefaultFailureMessage(invocation, operation));
    }

    public long getDefaultMaxResults() {
        return 999; // Some mediaservers will crash if you don't limit the maximum results
    }

    public void receivedRaw(ActionInvocation actionInvocation, String xml) {}
    public abstract void received(ActionInvocation actionInvocation, DIDLLite didl);
    public abstract void updateStatus(Status status);
    public abstract void failure(String failureMessage);

}
