/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.atolcd.parapheur.repo.patch;

import com.atolcd.parapheur.model.ParapheurModel;
import java.util.List;
import javax.transaction.UserTransaction;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.module.AbstractModuleComponent;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.search.SearchService;
import org.alfresco.service.cmr.security.AuthorityService;
import org.alfresco.service.cmr.security.AuthorityType;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.transaction.TransactionService;
import org.apache.log4j.Logger;

/**
 * Creates a role for each parapheur found in the parapheurs space.
 *
 * These roles are used for permissions.
 *
 * @author Vivien Barousse
 */
public class RoleParapheurOwnerPatch extends AbstractModuleComponent {

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

    public static final String ALL_PARAPHEURS_XPATH = "/app:company_home" +
            "/ph:parapheurs" +
            "/*";

    private NodeService nodeService;

    private SearchService searchService;

    private NamespaceService namespaceService;

    private AuthorityService authorityService;

    private TransactionService transactionService;

    private String store;

    @Override
    protected void executeInternal() throws Throwable {
        UserTransaction tx = transactionService.getUserTransaction();
        try {
            tx.begin();

            List<NodeRef> parapheursRef = searchService.selectNodes(getRootNode(),
                    ALL_PARAPHEURS_XPATH,
                    null,
                    namespaceService,
                    false);

            logger.info("Creating roles for " + parapheursRef.size() + " parapheurs");
            for (NodeRef parapheurRef : parapheursRef) {
                patch(parapheurRef);
            }
            
            tx.commit();
        } catch (Exception ex) {
            tx.rollback();
            throw new Exception("Unknown exception during patch", ex);
        }
    }

    protected void patch(NodeRef parapheur) {
        String parapheurName = (String) nodeService.getProperty(parapheur, ContentModel.PROP_NAME);
        String roleName = "PHOWNER_" + parapheurName;
        String authorityName = authorityService.getName(AuthorityType.ROLE, roleName);
        if (!authorityService.authorityExists(authorityName)) {
            authorityService.createAuthority(AuthorityType.ROLE, roleName);
            String phOwner = (String) nodeService.getProperty(parapheur, ParapheurModel.PROP_PROPRIETAIRE_PARAPHEUR);

            if (phOwner != null && phOwner.trim().length() > 0) {
                String ownerAuthority = authorityService.getName(AuthorityType.USER, phOwner);

                authorityService.addAuthority(authorityName, ownerAuthority);
            }
        }
    }

    protected NodeRef getRootNode() {
        return nodeService.getRootNode(new StoreRef(store));
    }
    
    public void setAuthorityService(AuthorityService authorityService) {
        this.authorityService = authorityService;
    }

    public void setNamespaceService(NamespaceService namespaceService) {
        this.namespaceService = namespaceService;
    }

    public void setNodeService(NodeService nodeService) {
        this.nodeService = nodeService;
    }

    public void setSearchService(SearchService searchService) {
        this.searchService = searchService;
    }

    public void setStore(String store) {
        this.store = store;
    }

    public void setTransactionService(TransactionService transactionService) {
        this.transactionService = transactionService;
    }

}
