HEX
Server: Microsoft-IIS/8.5
System: Windows NT YDAWBH120 6.3 build 9600 (Windows Server 2012 R2 Standard Edition) AMD64
User: tentjecom_web (0)
PHP: 7.4.14
Disabled: NONE
Upload Files
File: D:/HostingSpaces/bekkers/bekkersengineering.nl/resources/assets/js/kms/fileupload.ng.js
'use strict';
//inject directives and services.


var app = angular.module('fileUpload', ['ngFileUpload']);

app.controller('fileUploadController', ['$scope', 'Upload', '$timeout', function ($scope, Upload, $timeout) {
    console.log('fileuploadcontroller loading');

    //The files list
    //Todo, extend with the files form the database
    $scope.files = [];
    //These are the fileIds, used for saving

    $scope.dynamic = false;

    $scope.uploadSizes = '';

    $scope.maxImages;

    $scope.errorMsg = {};

    $scope.subFolder = false;

    $scope.attributeKey = '';

    $scope.forModel;
    $scope.forModelId;

    $scope.canUploadNewImage;

    /**
     * This function uploads the new files
     * @param files
     * @param errFiles
     * @param maximages
     * @param blockId
     * @param tabId optional
     */
    $scope.uploadFiles = function (files, errFiles, maximages, blockId, tabId) {
        console.log("upload for block with blockId: "+blockId+" and tabKey: "+tabId);
        console.log("uploadedFiles files:");
        console.log(files);

        //Get the model and the id where we are uploading images for. Should flow via a service but due to bad design and an upcoming newer angular version does not. todo: improve me
        var htmlElement = document.querySelector("[ng-controller=KmsAttributeDynamicController]");
        $scope.forModel = htmlElement.dataset.forModel;
        $scope.forModelId = htmlElement.dataset.forModelId;
        console.log("fileUploadController uploading files For model: "+$scope.forModel+" with id: "+$scope.forModelId+" and blockId: "+blockId);


        if (typeof $scope.files == 'undefined') $scope.files = [];
        if ($scope.files.length >= maximages) {
            console.log("File upload not allowed. "+$scope.files.length+"/"+maximages+" uploaded");
            return false;
        }
        //Set the files
        $scope.errFiles = errFiles;

        //Foreach each file
        angular.forEach(files, function (file) {

            //Push to true adds image at the back, false at the front
            var push = true;

            //Add the placeholder
            var loadingImage = {loading: true, thumb_image_url: '/images/kms/loading.gif'};

            if (push == true) {
                $scope.files.push(loadingImage);
                var imageKey = $scope.files.length - 1
            } else {
                //Add at the front
                $scope.files.unshift(loadingImage);
                var imageKey = 0
            }

            //Upload to the server
            file.upload = Upload.upload({
                url: '/kms/upload',
                data: {
                    //Sent the data and the options
                    file: file,
                    uploadSizes: $scope.uploadSizes,
                    dynamic: $scope.dynamic,
                    subFolder: $scope.subFolder,
                    attribute_key: $scope.attributeKey,
                    forModelName: $scope.forModel,
                    forModelId: $scope.forModelId,
                    forBlockId: blockId,
                    forTabId: tabId
                }
            });
            //After uploading
            file.upload.then(function (response) {
                $timeout(function () {
                    // delete $scope.files.loading
                    console.log(response);

                    //Set the response data

                    // file.result = response.data;
                    // file.result = response.data.uploaded[0];

                    // console.log("Thumb: "+response.data.uploaded.[0].thumb);
                    console.log("Image Id: "+response.data.uploaded[0].id);

                    //Add the file to the current files
                    $scope.files[imageKey] = response.data.uploaded[0];

                    console.log("$scope.files["+ imageKey +"] =");
                    console.log($scope.files[imageKey]);

                    //Reverse push
                    //Add the file to the current files
                    // $scope.files.unshift(file.result);
                    // $scope.setFileIds()

                    //Update fileids
                    var forBlockId = response.data.uploaded[0].forBlockId;

                    var blocksDataObject = $scope.getBlocksData(); //Defined in the KmsAttributeDynamicController

                    for(var key in blocksDataObject)
                    {
                        console.log("Looping over blocks to find a block with id: "+forBlockId+". Current block id: "+blocksDataObject[key].blockId);
                        // console.log(blocksDataObject[key]);

                        if(blocksDataObject.hasOwnProperty(key) === false || blocksDataObject[key].hasOwnProperty("blockId") === false) {
                            console.warn("Detected block data without a block id. Because of this, it is not possible to upload a file for that block. This does not mean that the uploaded image can be linked to the block your uploading currently for");
                            continue;
                        }

                        if(blocksDataObject[key].blockId == forBlockId) {
                            console.log("found block with id: "+forBlockId);

                            var data = [];
                            if(response.data.uploaded[0].forTabId) {
                                console.log("Uploaded an image for tab: "+response.data.uploaded[0].forTabId);
                                data = response.data.uploaded[0].id+"#"+response.data.uploaded[0].forTabId; //imageid#multipleimagesslot
                            } else {
                                console.log("Uploaded an image without tab: "+response.data.uploaded[0].id);
                                data = response.data.uploaded[0].id;
                            }

                            var fileIds = [];
                            if(blocksDataObject[key].hasOwnProperty('fileIds')) {
                                var length = blocksDataObject[key]['fileIds'].length;

                                //Determine if it is a single image or multiple images.
                                blocksDataObject[key]['fileIds'][length] = data;
                                console.log("Updating fileIds with image id: "+data);
                            } else {
                                console.log("Setting fileIds to a new array with image id: "+data);
                                blocksDataObject[key].fileIds = [data];
                            }

                            console.log("files.length = "+blocksDataObject[key].fileIds.length+" maxImages = "+$scope.maxImages);
                            $scope.canUploadNewImage = blocksDataObject[key].fileIds.length < $scope.maxImages;
                        }

                        $scope.setBlocksData(blocksDataObject);
                    }
                });
            }, function (response) {
                if (response.status > 0)
                    $scope.errorMsg = response.status + ': ' + response.data;
                    console.error("Error: "+$scope.errorMsg);
            }, function (evt) {
                file.progress = Math.min(100, parseInt(100.0 *
                    evt.loaded / evt.total));
            });
        });

    };

    $scope.deleteImage = function (index, blockId, tab_key) {
        var idToDelete = $scope.files[index].id;
        console.log("idToDelete: "+idToDelete+" from blockId: "+blockId);

        //Delete the image
        $scope.files.splice(index, 1);
        console.log("Current image amount: "+$scope.files.length);

        //Delete the image id
        // $scope.setFileIds()

        var blocksDataObject = $scope.getBlocksData(); //Defined in the KmsAttributeDynamicController

        for(var blockIndex in blocksDataObject)
        {
            if(blocksDataObject.hasOwnProperty(blockIndex) === false || blocksDataObject[blockIndex].hasOwnProperty("blockId") === false) {
                console.warn("Detected block data without a block id. Because of this, it is not possible to upload a file for that block. This does not mean that the uploaded image can be linked to the block your uploading currently for");
                continue;
            }

            if(blocksDataObject[blockIndex].blockId == blockId) {
                console.log("found block with id: " + blockId);

                if(blocksDataObject[blockIndex].hasOwnProperty('fileIdsToDelete') === false) blocksDataObject[blockIndex].fileIdsToDelete = [];

                console.log("Current files to delete: "+blocksDataObject[blockIndex].fileIdsToDelete);
                idToDelete = (typeof tab_key !== 'undefined') ? idToDelete+"#"+tab_key : idToDelete ;

                for(var index in blocksDataObject[blockIndex].fileIds)
                {
                    var currentId = blocksDataObject[blockIndex].fileIds[index];
                    if(typeof tab_key !== 'undefined') {
                        console.log("Looping over the file ids to find an image with id: "+idToDelete+" for tab: "+tab_key+" ("+currentId+")");
                    } else {
                        console.log("Looping over the file ids to find an image with id: "+idToDelete);
                    }

                    if(currentId == idToDelete) {
                        console.log("Image marked to delete on save: "+idToDelete);
                        blocksDataObject[blockIndex].fileIdsToDelete[blocksDataObject[blockIndex].fileIdsToDelete.length] = idToDelete;

                        blocksDataObject[blockIndex].fileIds.splice(index, 1);

                        if(typeof tab_key === 'undefined') {
                            $scope.canUploadNewImage = blocksDataObject[blockIndex].fileIds.length < $scope.maxImages;
                        } else {
                            var count = 0;
                            for(var index in blocksDataObject[blockIndex].fileIds) {
                                if(blocksDataObject[blockIndex].fileIds[index].split("#")[1] == tab_key) {
                                    count++;
                                }
                            }

                            $scope.canUploadNewImage = count < $scope.maxImages;
                        }
                        break;
                    }
                }
            }
        }

        $scope.setBlocksData(blocksDataObject);

        delete $scope.errorMsg.toMany;
    };

    // $scope.moveImage = function (index, direction) {
    //     var currentFile = $scope.files[index]
    //     var currentFileId = $scope.fileIds[index]
    //
    //     if (direction == 'left') {
    //         $scope.files[index] = $scope.files[index - 1];
    //         $scope.files[index - 1] = currentFile;
    //     } else {
    //         $scope.files[index] = $scope.files[index + 1];
    //         $scope.files[index + 1] = currentFile;
    //     }
    //     $scope.setFileIds()
    // };

    $scope.initFiles = function (files, maxImages, tab_key) {
        console.log("fileupload:initFiles: "+files+" maxImages: "+maxImages);

        if(files) {
            // //Strip out the image ids that do not belong to the tab we are processing for
            var filesToUse = [];
            if(typeof tab_key !== 'undefined') {
                for(var index in files) {
                    var split = files[index].split("#");
                    if(split.length !== 2) continue; //The imageId did not contain a #

                    if(split[1] != tab_key) {
                        console.log("fileupload:initFiles: Ignoring image with id: "+split[0]+" because it belongs to tab "+split[1]+" and we are processing images for tab "+tab_key);
                    } else {
                        filesToUse[filesToUse.length] = files[index];
                    }
                }
            } else {
                filesToUse = files;
            }

            if(filesToUse.length > 0) {
                $.ajax({
                    type: "POST",
                    url: "/kms/getimagedata",
                    data: {
                        fileIds: filesToUse
                    },
                    success: function (response) {
                        console.log("Retrieved files: ");
                        console.log(response);

                        // files must look like this files[index].id files[index].sizes
                        $scope.files = response;

                        // $scope.setFileIds();
                        if (typeof maxImages != 'undefined') {
                            $scope.maxImages = maxImages
                        }

                        console.log("files.length < $scope.maxImages: " + filesToUse.length < $scope.maxImages);
                        $scope.canUploadNewImage = filesToUse.length < $scope.maxImages;

                        $scope.$apply();
                    },
                    error: function () {
                        console.log("An error occured while retrieving image(s)")
                    },
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    dataType: 'json'
                });
            } else {
                $scope.maxImages = maxImages;
                $scope.canUploadNewImage = true;
                $scope.files = [];
            }
        } else {
            $scope.maxImages = maxImages;
            $scope.canUploadNewImage = true;
            $scope.files = [];
        }
    };

    $scope.updateFiles = function(files) {
        console.log("Updated files");
        $scope.files = files;
    };


    // $scope.setFileIds = function () {
    //     var local_fileIds = [];
    //
    //     angular.forEach($scope.files, function (file) {
    //         local_fileIds.push(file.id);
    //     });
    //
    //     console.log("set file ids ($scope.fileIds):");
    //     console.log(local_fileIds);
    //     $scope.fileIds = local_fileIds
    // };


    // $scope.getFileCount = function () {
    //     return $scope.fileIds.length;
    // };

    $scope.sortableOptions = {
        update: function (e, ui) {
            ui.item.sortable.cancel();
            var originalIndex = ui.item.sortable.index;
            var newIndex = ui.item.sortable.dropindex

            var oldImage = $scope.files[originalIndex]
            $scope.files[originalIndex] = $scope.files[newIndex]
            $scope.files[newIndex] = oldImage
            $scope.setFileIds()

        }

    };

    console.log('fileuploadcontroller initialized');
}]);