/*******************************************************************************
 * Copyright 2012 Apigee Corporation
 * 
 * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package org.usergrid.services.applications;

import static org.usergrid.services.ServiceResults.genericServiceResults;
import static org.usergrid.services.ServiceResults.simpleServiceResults;
import static org.usergrid.utils.MapUtils.hashMap;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.usergrid.persistence.Entity;
import org.usergrid.persistence.EntityRef;
import org.usergrid.persistence.Query;
import org.usergrid.persistence.Results;
import org.usergrid.services.AbstractService;
import org.usergrid.services.ServiceContext;
import org.usergrid.services.ServiceParameter.QueryParameter;
import org.usergrid.services.ServicePayload;
import org.usergrid.services.ServiceResults;
import org.usergrid.services.ServiceResults.Type;

public class ApplicationsService extends AbstractService {

    private static final Logger logger = LoggerFactory
            .getLogger(ApplicationsService.class);

    public ApplicationsService() {
        super();
        logger.info("/applications");
        declareEntityDictionary("counters");
        declareEntityCommand("hello");
        declareEntityCommand("resetroles");
    }

    @Override
    public ServiceResults invoke(ServiceContext context) throws Exception {

        ServiceResults results = null;

        String metadataType = checkForServiceMetadata(context);
        if (metadataType != null) {
            return handleServiceMetadata(context, metadataType);
        }

        String entityDictionary = checkForEntityDictionaries(context);
        String entityCommand = checkForEntityCommands(context);

        results = invokeItemWithId(context, sm.getApplicationId());
        context.dequeueParameter();

        results = handleEntityDictionary(context, results, entityDictionary);
        results = handleEntityCommand(context, results, entityCommand);

        return results;
    }

    @Override
    public ServiceResults getItemById(ServiceContext context, UUID id)
            throws Exception {
        return getApplicationEntity(context);
    }

    @Override
    public ServiceResults putItemById(ServiceContext context, UUID id)
            throws Exception {
        return updateApplicationEntity(context, context.getPayload());
    }

    @Override
    public ServiceResults getEntityDictionary(ServiceContext context, List<EntityRef> refs, String dictionary)
            throws Exception {

        if ("counters".equals(dictionary)) {
            checkPermissionsForPath(context, "/counters");

            if (context.parameterCount() == 0) {
                return getApplicationCounterNames();
            } else if (context.parameterCount() > 0) {
                if (context.getParameters().get(0) instanceof QueryParameter) {
                    return getApplicationCounters(((QueryParameter) context.getParameters().get(0)).getQuery());
                }
            }
        }

        return super.getEntityDictionary(context, refs, dictionary);
    }


    public ServiceResults getApplicationEntity(ServiceContext context)
            throws Exception {

        checkPermissionsForPath(context, "/");

        Entity entity = em.get(em.getApplicationRef());
        Results r = Results.fromEntity(entity);

        Map<String, Object> collections = em.getApplicationCollectionMetadata();
        // Set<String> collections = em.getApplicationCollections();
        if (collections.size() > 0) {
            r.setMetadata(em.getApplicationRef().getUuid(), "collections",
                    collections);
        }

        return genericServiceResults(r);
    }

    public ServiceResults updateApplicationEntity(ServiceContext context,
            ServicePayload payload) throws Exception {

        checkPermissionsForPath(context, "/");

        Map<String, Object> properties = payload.getProperties();
        Object m = properties.get("metadata");
        if (m instanceof Map) {
            @SuppressWarnings("unchecked")
            Map<String, Object> metadata = (Map<String, Object>) m;
            Object c = metadata.get("collections");
            if (c instanceof Map) {
                @SuppressWarnings("unchecked")
                Map<String, Object> collections = (Map<String, Object>) c;
                for (String collection : collections.keySet()) {
                    em.createApplicationCollection(collection);
                    logger.info("Created collection " + collection
                            + " for application " + sm.getApplicationId());
                }
            }
        }

        Entity entity = em.get(em.getApplicationRef());
        em.updateProperties(entity, properties);
        entity.addProperties(properties);
        Results r = Results.fromEntity(entity);

        Set<String> collections = em.getApplicationCollections();
        if (collections.size() > 0) {
            r.setMetadata(em.getApplicationRef().getUuid(), "collections",
                    collections);
        }

        return genericServiceResults(r);
    }

//    public ServiceResults getApplicationRoles() throws Exception {
//        Map<String, String> roles = em.getRoles();
//        ServiceResults results = genericServiceResults().withData(roles);
//        return results;
//    }

//    public ServiceResults newApplicationRole(String roleName, String roleTitle,
//            long inactivity) throws Exception {
//        em.createRole(roleName, roleTitle, inactivity);
//        return getApplicationRoles();
//    }
//
//    public ServiceResults deleteApplicationRole(String roleName)
//            throws Exception {
//        em.deleteRole(roleName);
//        return getApplicationRoles();
//    }

//    public ServiceResults getApplicationRolePermissions(String roleName)
//            throws Exception {
//        Set<String> permissions = em.getRolePermissions(roleName);
//        ServiceResults results = genericServiceResults().withData(permissions);
//        return results;
//    }

//    public ServiceResults grantApplicationRolePermission(String roleName,
//            String permission) throws Exception {
//        em.grantRolePermission(roleName, permission);
//        return getApplicationRolePermissions(roleName);
//    }
//
//    public ServiceResults revokeApplicationRolePermission(String roleName,
//            String permission) throws Exception {
//        em.revokeRolePermission(roleName, permission);
//        return getApplicationRolePermissions(roleName);
//    }

    public ServiceResults getApplicationCounterNames() throws Exception {
        Set<String> counters = em.getCounterNames();
        ServiceResults results = genericServiceResults().withData(counters);
        return results;
    }

    public ServiceResults getApplicationCounters(Query query) throws Exception {
        Results counters = em.getAggregateCounters(query);
        ServiceResults results = simpleServiceResults(Type.COUNTERS);
        if (counters != null) {
            results.withCounters(counters.getCounters());
        }
        return results;
    }

    @Override
    public ServiceResults getEntityCommand(ServiceContext context,
            List<EntityRef> refs, String command) throws Exception {
        if ("hello".equalsIgnoreCase(command)) {
            ServiceResults results = genericServiceResults().withData(
                    hashMap("say", "Hello!"));
            return results;
        }
        return super.getEntityCommand(context, refs, command);
    }

    @Override
    public ServiceResults postEntityCommand(ServiceContext context,
            List<EntityRef> refs, String command, ServicePayload payload)
            throws Exception {
        if ("resetroles".equalsIgnoreCase(command)) {
            em.resetRoles();
//          TODO TN finish this  return getApplicationRoles();
        }
        return super.postEntityCommand(context, refs, command, payload);
    }

}

@@ -5860,1466 +5860,8 @@
  %7D%0A%0A
-//    public ServiceResults getApplicationRoles() throws Exception %7B%0A//        Map%3CString, String%3E roles = em.getRoles();%0A//        ServiceResults results = genericServiceResults().withData(roles);%0A//        return results;%0A//    %7D%0A%0A//    public ServiceResults newApplicationRole(String roleName, String roleTitle,%0A//            long inactivity) throws Exception %7B%0A//        em.createRole(roleName, roleTitle, inactivity);%0A//        return getApplicationRoles();%0A//    %7D%0A//%0A//    public ServiceResults deleteApplicationRole(String roleName)%0A//            throws Exception %7B%0A//        em.deleteRole(roleName);%0A//        return getApplicationRoles();%0A//    %7D%0A%0A//    public ServiceResults getApplicationRolePermissions(String roleName)%0A//            throws Exception %7B%0A//        Set%3CString%3E permissions = em.getRolePermissions(roleName);%0A//        ServiceResults results = genericServiceResults().withData(permissions);%0A//        return results;%0A//    %7D%0A%0A//    public ServiceResults grantApplicationRolePermission(String roleName,%0A//            String permission) throws Exception %7B%0A//        em.grantRolePermission(roleName, permission);%0A//        return getApplicationRolePermissions(roleName);%0A//    %7D%0A//%0A//    public ServiceResults revokeApplicationRolePermission(String roleName,%0A//            String permission) throws Exception %7B%0A//        em.revokeRolePermission(roleName, permission);%0A//        return getApplicationRolePermissions(roleName);%0A//    %7D%0A%0A
     

Remove unused methods