<commit_before>/*
 * Copyright (c) <NAME>. All rights reserved.
 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
 */

package org.fundacionjala.gradle.plugins.enforce.tasks.salesforce.retrieve

import org.fundacionjala.gradle.plugins.enforce.utils.Constants
import com.sforce.soap.metadata.PackageTypeMembers
import org.fundacionjala.gradle.plugins.enforce.utils.AnsiColor
import org.fundacionjala.gradle.plugins.enforce.utils.ManagementFile
import org.fundacionjala.gradle.plugins.enforce.utils.Util
import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.PackageBuilder

import java.nio.file.Paths

/**
 * Retrieves elements from organization according parameters inserted by user
 */
class Retrieve extends Retrieval {
    private static final String GROUP_OF_TASK = "Retrieve"
    private static final String DESCRIPTION_OF_TASK = 'This task recover specific files from an organization'
    private static final String MESSAGE_WARNING = 'Warning: Your files will be replaced if there are.'
    private static final String MESSAGE_CANCELED = 'Retrieve task was canceled!!'
    private static final String QUESTION_TO_CONTINUE = 'Do you want to continue? (y/n) : '
    private final String FILES_RETRIEVE = 'files'
    private final String DESTINATION_FOLDER = 'destination'
    private final String COMMA = ','
    private final String YES = 'y'
    private String option
    public static final String WILDCARD = '*'
    public String files
    public String destination
    public final String SLASH = '/'
    public final String BACKSLASH = '\\\\'

    /**
     * Sets description and group task
     * @param description is description tasks
     * @param group is the group typeName the task
     */
    Retrieve() {
        super(DESCRIPTION_OF_TASK, GROUP_OF_TASK)
    }

    @Override
    void runTask() {
        verifyDestinationFolder()
        ManagementFile.createDirectories(projectPath)
        verifyFiles()
        validateContentParameter()
        if (!hasPackage() && !files) {
            showWarningMessage()
            if (option == YES) {
                retrieveWithoutPackageXml()
            } else {
                logger.warn(MESSAGE_CANCELED)
            }
        } else {
            showInfoMessage()
            retrieveWithPackageXml()
        }
    }

    /**
     * Loads the destination parameter
     */
    private void verifyDestinationFolder() {
        if (destination) {
            projectPath = Paths.get(destination).isAbsolute() ? destination :
                    Paths.get(project.projectDir.absolutePath, destination).toString()
            return
        }

        if (Util.isValidProperty(project, DESTINATION_FOLDER)) {
            String targetPath = project.property(DESTINATION_FOLDER) as String
            projectPath = Paths.get(targetPath).isAbsolute() ? targetPath :
                    Paths.get(project.projectDir.absolutePath, targetPath).toString()
        }
    }

    /**
     * Loads the files parameter
     */
    private void verifyFiles() {
        if (!files) {
            if (Util.isValidProperty(project, FILES_RETRIEVE)) {
                files = project.property(FILES_RETRIEVE) as String
            }
        }
    }

    /**
     * Gets a files array from a directory
     * @param directory the directory to get its files
     * @return a files array
     */
    File[] getFiles(File directory) {
        File[] arrayFiles = []
        if (directory && directory.isDirectory()) {
            arrayFiles = directory.listFiles()
        }
        return arrayFiles
    }

    /**
     * Executes the logic to retrieve without update the package.xml file
     */
    void retrieveWithoutPackageXml() {
        createPackageByFolders()
        runRetrieve()
        copyAllFiles()
        resetFileTracking()
    }

    /**
     * Executes the logic to retrieve updating the package.xml file
     */
    void retrieveWithPackageXml() {
        createPackage()
        runRetrieve()
        copyFilesWithoutPackage()
        updatePackageXml(Paths.get(unPackageFolder, Constants.PACKAGE_FILE_NAME).toString(), Paths.get(projectPath, Constants.PACKAGE_FILE_NAME).toString())
        File unpackage = new File(unPackageFolder)
        unpackage.deleteDir()
    }

    /**
     * Verifies if exist package xml into project path
     * @return true if exist a package xml file else return false<commit_msg>added enhancement about warning messages on retrieve task<commit_after>/*
 * Copyright (c) <NAME>. All rights reserved.
 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
 */

package org.fundacionjala.gradle.plugins.enforce.tasks.salesforce.retrieve

import org.fundacionjala.gradle.plugins.enforce.utils.Constants
import com.sforce.soap.metadata.PackageTypeMembers
import org.fundacionjala.gradle.plugins.enforce.utils.AnsiColor
import org.fundacionjala.gradle.plugins.enforce.utils.ManagementFile
import org.fundacionjala.gradle.plugins.enforce.utils.Util
import org.fundacionjala.gradle.plugins.enforce.utils.salesforce.PackageBuilder

import java.nio.file.Paths

/**
 * Retrieves elements from organization according parameters inserted by user
 */
class Retrieve extends Retrieval {
    private static final String GROUP_OF_TASK = "Retrieve"
    private static final String DESCRIPTION_OF_TASK = 'This task recover specific files from an organization'
    private static final String MESSAGE_WARNING = 'Warning: All files according to package will be downloaded'
    private static final String MESSAGE_CANCELED = 'Retrieve task was canceled!!'
    private static final String QUESTION_TO_CONTINUE = 'Do you want to continue? (y/n) : '
    private final String FILES_RETRIEVE = 'files'
    private final String DESTINATION_FOLDER = 'destination'
    private final String COMMA = ','
    private final String YES = 'y'
    private String option
    public static final String WILDCARD = '*'
    public String files
    public String destination
    public final String SLASH = '/'
    public final String BACKSLASH = '\\\\'

    /**
     * Sets description and group task
     * @param description is description tasks
     * @param group is the group typeName the task
     */
    Retrieve() {
        super(DESCRIPTION_OF_TASK, GROUP_OF_TASK)
    }

    @Override
    void runTask() {
        verifyDestinationFolder()
        ManagementFile.createDirectories(projectPath)
        verifyFiles()
        validateContentParameter()
        if (!hasPackage() && !files) {
           retrieveWithoutPackageXml()
        } else {
            if(files){
                showInfoMessage()
                createPackageFromFiles()
            }else{
                showWarningMessage()
                if (option == YES) {
                    loadFromPackage()
                } else {
                    logger.warn(MESSAGE_CANCELED)
                    System.exit(0)
                }
            }
            retrieveWithPackageXml()
        }
    }

    /**
     * Creates the package xml file from files parameter
     */
    private void createPackageFromFiles(){
        ArrayList<File> filesRetrieve = new ArrayList<File>()
        ArrayList<String> arrayNameArchives = files.split(COMMA)
        arrayNameArchives.each { nameFile ->
            filesRetrieve.push(new File(nameFile))
        }
        packageBuilder.createPackage(filesRetrieve)
    }

    /**
     * Loads the package structure file from package xml
     */
    private void loadFromPackage(){
        FileReader packageFileReader = new FileReader(Paths.get(projectPath, Constants.PACKAGE_FILE_NAME).toString())
        packageBuilder.read(packageFileReader)
    }

    /**
     * Loads the destination parameter
     */
    private void verifyDestinationFolder() {
        if (destination) {
            projectPath = Paths.get(destination).isAbsolute() ? destination :
                    Paths.get(project.projectDir.absolutePath, destination).toString()
            return
        }

        if (Util.isValidProperty(project, DESTINATION_FOLDER)) {
            String targetPath = project.property(DESTINATION_FOLDER) as String
            projectPath = Paths.get(targetPath).isAbsolute() ? targetPath :
                    Paths.get(project.projectDir.absolutePath, targetPath).toString()
        }
    }

    /**
     * Loads the files parameter
     */
    private void verifyFiles() {
        if (!files) {
            if (Util.isValidProperty(project, FILES_RETRIEVE)) {
                files = project.property(FILES_RETRIEVE) as String
            }
        }
    }

    /**
     * Gets a files array from a directory
     * @param directory the directory to get its files
     * @return a files array
     */
    File[] getFiles(File directory) {
        File[] arrayFiles = []
        if (directory && directory.isDirectory()) {
            arrayFiles = directory.listFiles()
        }
        return arrayFiles
    }

    /**
     * Executes the logic to retrieve without update the package.xml file
     */
    void retrieveWithoutPackageXml() {
        createPackageByFolders()
        runRetrieve()
        copyAllFiles()
        resetFileTracking()
    }

    /**
     * Executes the logic to retrieve updating the package.xml file
     */
    void retrieveWithPackageXml() {
        runRetrieve()
        copyFilesWithoutPackage()
        updatePackageXml(Paths.get(unPackageFolder, Constants.PACKAGE_FILE_NAME).toString(), Paths.get(projectPath, Constants.PACKAGE_FILE_NAME).toString())
        File unpackage = new File(unPackageFolder)
        unpackage.deleteDir()
    }

    /**
     * Verifies if exist package xml into project path
     * @return true if exist a package xml file else return false
{'fraction_non_alphanumeric': 0.08324831667006734, 'fraction_numerical': 0.00010201999591920016, 'mean_word_length': 2.5249910104279034, 'pattern_counts': {'":': 0, '<': 8, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 10}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4745560', 'n_tokens_mistral': 2608, 'n_tokens_neox': 2545, 'n_words': 690}