/**
 * JBoss, Home of Professional Open Source.
 * Copyright 2014 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * 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.jboss.pnc.coordinator;

import org.jboss.pnc.model.Artifact;
import org.jboss.pnc.model.BuildConfigSetRecord;
import org.jboss.pnc.model.BuildRecord;
import org.jboss.pnc.spi.datastore.repositories.ArtifactRepository;
import org.jboss.pnc.spi.datastore.repositories.BuildConfigSetRecordRepository;
import org.jboss.pnc.spi.datastore.repositories.BuildRecordRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * Bean providing an interface to delete temporary builds
 *
 * @author Jakub Bartecek
 */
@ApplicationScoped
public class TemporaryBuildsCleaner {
    private final Logger log = LoggerFactory.getLogger(TemporaryBuildsCleaner.class);

    private BuildRecordRepository buildRecordRepository;

    private BuildConfigSetRecordRepository buildConfigSetRecordRepository;

    private ArtifactRepository artifactRepository;

    @Deprecated
    public TemporaryBuildsCleaner() {
    }

    @Inject
    public TemporaryBuildsCleaner(BuildRecordRepository buildRecordRepository, BuildConfigSetRecordRepository buildConfigSetRecordRepository,
                                  ArtifactRepository artifactRepository) {
        this.buildRecordRepository = buildRecordRepository;
        this.buildConfigSetRecordRepository = buildConfigSetRecordRepository;
        this.artifactRepository = artifactRepository;
    }

    /**
     * Deletes a temporary build and artifacts created during the build or orphan dependencies used
     *
     * @param buildRecord BuildRecord to be deleted
     */
    public void deleteTemporaryBuild(BuildRecord buildRecord) {
        if (!buildRecord.isTemporaryBuild())
            throw new IllegalArgumentException("Only deletion of the temporary builds is allowed");
        log.info("Starting deletion of a temporary build " + buildRecord);

        /** Delete relation between BuildRecord and Artifact */
        Set<Artifact> artifactsToBeDeleted = new HashSet<>();

        removeDependencyRelationBuildRecordArtifact(buildRecord, artifactsToBeDeleted, true);
        removeDependencyRelationBuildRecordArtifact(buildRecord, artifactsToBeDeleted, false);

        /**
         * Delete artifacts, if the artifacts are not used in other builds
         */
        for(Artifact artifact : artifactsToBeDeleted) {
            log.info("Deleting temporary artifact: " + artifact.getDescriptiveString());
            artifactRepository.delete(artifact.getId());
        }

        buildRecordRepository.delete(buildRecord.getId());
    }

    public void deleteTemporaryBuildConfigSetRecord(BuildConfigSetRecord buildConfigSetRecord) {
        if (!buildConfigSetRecord.isTemporaryBuild())
            throw new IllegalArgumentException("Only deletion of the temporary builds is allowed");
        log.info("Starting deletion of a temporary build record set " + buildConfigSetRecord);

        buildConfigSetRecord.getBuildRecords().forEach(br -> deleteTemporaryBuild(br));
        buildConfigSetRecordRepository.delete(buildConfigSetRecord.getId());

        log.info("Deletion of a temporary build record set finished: " + buildConfigSetRecord);
    }

    private void removeDependencyRelationBuildRecordArtifact(BuildRecord buildRecord, Set<Artifact> artifactsToBeDeleted,
                                                             boolean applyToBuiltArtifacts) {
        Set<Artifact> builtArtifacts = buildRecord.getBuiltArtifacts();
        for (Artifact artifact : builtArtifacts) {
            log.info(String.format("Deleting relation BR-Artifact. BuiltArtifacts? %s, BR=%s, artifact=%s", applyToBuiltArtifacts,
                    buildRecord, artifact.getDescriptiveString()));

            if (artifact.getDistributedInProductMilestones().size() != 0) {
                log.error("Temporary artifact was distributed in milestone! Artifact: "
                        + artifact.toString() + "\n Milestones: " + artifact.getDistributedInProductMilestones().toString());
                continue;
            }

            if (applyToBuiltArtifacts)
                artifact.getBuildRecords().remove(buildRecord);
            else
                artifact.getDependantBuildRecords().remove(buildRecord);

            artifactRepository.save(artifact);
            artifactsToBeDeleted.add(artifact);
        }

        if (applyToBuiltArtifacts)
            buildRecord.setBuiltArtifacts(Collections.emptySet());
        else
            buildRecord.setDependencies(Collections.emptySet());

        buildRecordRepository.save(buildRecord);
    }

}

@@ -1136,16 +1136,126 @@
 ctory;%0A%0A
+import javax.ejb.Stateless;%0Aimport javax.ejb.TransactionAttribute;%0Aimport javax.ejb.TransactionAttributeType;%0A
 import j
@@ -1500,33 +1500,25 @@
 ek%0A */%0A@
-ApplicationScoped
+Stateless
 %0Apublic 
@@ -2439,17 +2439,25 @@
  @param 
-b
+detachedB
 uildReco
@@ -2534,33 +2534,41 @@
 ild(BuildRecord 
-b
+detachedB
 uildRecord) %7B%0A  
@@ -2574,25 +2574,33 @@
        if (!
-b
+detachedB
 uildRecord.i
@@ -2730,72 +2730,312 @@
     
-log.info(%22Starting deletion of a temporary build %22 + buildRecord
+BuildRecord buildRecord = buildRecordRepository.findByIdFetchAllProperties(detachedBuildRecord.getId());%0A        log.info(%22Starting deletion of a temporary build %22 + buildRecord + %22; Built artifacts: %22 + buildRecord.getBuiltArtifacts()%0A                + %22; Dependencies: %22 + buildRecord.getDependencies()
 );%0A%0A
@@ -3725,24 +3725,202 @@
 ());%0A    %7D%0A%0A
+    /**%0A     * Deletes a BuildConfigSetRecord and BuildRecords produced in the build%0A     *%0A     * @param detachedBuildConfigSetRecord BuildConfigSetRecord to be deleted%0A     */%0A
     public v
@@ -3976,25 +3976,33 @@
 igSetRecord 
-b
+detachedB
 uildConfigSe
@@ -4025,17 +4025,25 @@
    if (!
-b
+detachedB
 uildConf
@@ -4166,32 +4166,164 @@
 s is allowed%22);%0A
+        BuildConfigSetRecord buildConfigSetRecord = buildConfigSetRecordRepository.queryById(detachedBuildConfigSetRecord.getId());%0A
         log.info
@@ -4913,57 +4913,202 @@
 ct%3E 
-builtArtifacts = buildRecord.getBuiltArtifacts();
+artifacts;%0A        if (applyToBuiltArtifacts)%7B%0A            artifacts = buildRecord.getBuiltArtifacts();%0A        %7D%0A        else %7B%0A            artifacts = buildRecord.getDependencies();%0A        %7D%0A
 %0A   
@@ -5141,14 +5141,9 @@
 t : 
-builtA
+a
 rtif

Fix TemporaryBuildsCleaner to work with detached entities and lazy loading