/*
 * 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.ui;

import org.teleal.cling.model.action.ActionException;
import org.teleal.cling.model.action.ActionInvocation;
import org.teleal.cling.model.meta.DeviceService;
import org.teleal.cling.support.contentdirectory.descriptor.didl.DIDLLite;
import org.teleal.cling.support.contentdirectory.descriptor.didl.Container;
import org.teleal.cling.support.contentdirectory.descriptor.didl.Item;
import org.teleal.cling.support.contentdirectory.descriptor.DIDLParser;
import org.teleal.cling.support.contentdirectory.BrowseActionCallback;
import org.teleal.cling.model.types.ErrorCode;

import java.util.logging.Logger;

import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.SwingUtilities;
import java.util.ArrayList;
import java.util.List;

/**
 *
 */
public abstract class ContentBrowseActionCallback extends BrowseActionCallback {

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

    final protected DefaultTreeModel treeModel;
    final protected DefaultMutableTreeNode treeNode;

    public ContentBrowseActionCallback(DeviceService service, DefaultTreeModel treeModel, DefaultMutableTreeNode treeNode) {
        super(service, ((Container) treeNode.getUserObject()).getId(), true, "*", 0, null, "+dc:title");
        this.treeModel = treeModel;
        this.treeNode = treeNode;
    }

    public ContentBrowseActionCallback(DeviceService service, DefaultTreeModel treeModel, DefaultMutableTreeNode treeNode,
                                       String filter, long firstResult, long maxResults, String orderBy) {
        super(service, ((Container) treeNode.getUserObject()).getId(), true, filter, firstResult, maxResults, orderBy);
        this.treeModel = treeModel;
        this.treeNode = treeNode;
    }

    public DefaultTreeModel getTreeModel() {
        return treeModel;
    }

    public DefaultMutableTreeNode getTreeNode() {
        return treeNode;
    }

    public void received(final ActionInvocation actionInvocation, DIDLLite didl) {
        log.fine("Received browse action DIDL descriptor, creating tree nodes");
        final List<DefaultMutableTreeNode> childNodes = new ArrayList();

        try {

            // Containers first
            for (Container childContainer : DIDLParser.getChildren(didl, Container.class)) {
                DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(childContainer) {
                    @Override
                    public boolean isLeaf() {
                        return ((Container) getUserObject()).getChildCount() <= 0;
                    }
                };
                childNodes.add(childNode);
            }

            // Now items
            for (Item childItem : DIDLParser.getChildren(didl, Item.class)) {
                DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(childItem) {
                    @Override
                    public boolean isLeaf() {
                        return true;
                    }
                };
                childNodes.add(childNode);
            }

        } catch (Exception ex) {
            log.fine("Creating DIDL tree nodes failed: " + ex);
            actionInvocation.setFailure(
                    new ActionException(ErrorCode.ACTION_FAILED, "Can't create tree child nodes: " + ex, ex)
            );
            failure(actionInvocation, null);
        }

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                updateTreeModel(childNodes);
            }
        });
    }

    public void updateStatus(final Status status) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                updateStatusUI(status, treeNode, treeModel);
            }
        });
    }

    public void failure(final String failureMessage) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                failureUI(failureMessage);
            }
        });
    }

    protected void updateTreeModel(final List<DefaultMutableTreeNode> childNodes) {
        log.fine("Adding nodes to tree: " + childNodes.size());
        // Remove all "old" children such as the loading/progress messages
        removeChildren();

        // Insert new children
        for (DefaultMutableTreeNode childNode : childNodes) {
            insertChild(childNode);
        }
    }

    protected void removeChildren() {
        treeNode.removeAllChildren();
        treeModel.nodeStructureChanged(treeNode);
    }

    protected void insertChild(MutableTreeNode childNode) {
        int index = treeNode.getChildCount() <= 0 ? 0 : treeNode.getChildCount();
        treeModel.insertNodeInto(childNode, treeNode, index);
    }

    public abstract void updateStatusUI(Status status, DefaultMutableTreeNode treeNode, DefaultTreeModel treeModel);

    public abstract void failureUI(String failureMessage);
}
