/*
 * 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 Affero 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero 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.DeviceService;
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(DeviceService service, String containerId, boolean directChildren) {
        this(service, containerId, directChildren, "*", 0, null, null);
    }

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

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

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

        try {
            getActionInvocation().getInput().addValue(containerId);
            getActionInvocation().getInput().addValue(directChildren ? "BrowseDirectChildren" : "BrowseMetadata");
            getActionInvocation().getInput().addValue(filter);
            getActionInvocation().getInput().addValue(new UnsignedIntegerFourBytes(firstResult));
            getActionInvocation().getInput().addValue(
                    new UnsignedIntegerFourBytes(maxResults == null ? getDefaultMaxResults() : maxResults)
            );
            getActionInvocation().getInput().addValue(orderBy);
        } catch (ActionException ex) {
            throw new RuntimeException(ex);
        }
    }

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

    public void success(ActionInvocation actionInvocation) {
        log.fine("Successful browse action, reading output argument values");
        ActionArgumentValue[] output = actionInvocation.getOutput().getValues();

        String didlXML = output[0].getValue().toString();
        Long numberReturned = ((UnsignedIntegerFourBytes) output[1].getValue()).getValue();
        Long totalMatches = ((UnsignedIntegerFourBytes) output[2].getValue()).getValue();

        if (numberReturned > 0 &&  didlXML.length() > 0) {
            try {

/*
                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(actionInvocation, 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) {
                actionInvocation.setFailure(
                        new ActionException(ErrorCode.ACTION_FAILED, "Can't parse DIDL XML response: " + ex, ex)
                );
                failure(actionInvocation, null);
            }
        } else {
            received(actionInvocation, null);
            updateStatus(Status.OK);
        }
    }

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

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

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

}
