/**
 * Created by jaskokoyn on 4/25/2015.
 */
owlChatApp.controller("filesCtrl", ["$scope", "$rootScope", "$timeout", "$http", function($scope, $rootScope, $timeout, $http){
    $scope.myFiles                  =   [];

    $http({
        method: 'POST',
        url: 'actions/files/get-files.php'
    }).success(function(data,status,headers,config){
        if(data.status == 1){
            $("#filesModal").modal('hide');
            return null;
        }
        data.files.forEach(function(ele,ind,arr){
            $scope.myFiles.push(ele);
        });
        $timeout(function(){
            $(".btnTooltip").tooltip();
        }, 500);
    });

    $scope.dropzone                 =   new Dropzone(".fileDropzone", {
        url: "actions/files/upload.php",
        previewsContainer: "#fileDropzoneProgress",
        acceptedFiles: '.jpg,.pdf,.png',
        paramName: 'file',
        previewTemplate: '<div class="dz-preview dz-file-preview">' +
        '<div class="dz-details">' +
        '<div class="dz-filename"><span data-dz-name></span></div>' +
        '<div class="progress">' +
        '<div class="progress-bar progress-bar-info progress-bar-striped active" data-dz-uploadprogress>' +
        '</div>' +
        '</div>' +
        '</div>'
    });
    $scope.dropzone.on( "error", function(file, errorMessage, xhr ){
        console.log(errorMessage, xhr);
        $(file.previewElement).remove();
    });
    $scope.dropzone.on( "success", function(file, res){
        $(file.previewElement).remove();

        res             =   JSON.parse(res);

        if(res.status == 2){
            toastr.success("File uploaded.", "Success!");
        }else{
            toastr.error("Unable to upload file. Try again later.", "Warning!");
            return null;
        }

        $scope.$apply(function(){
            $scope.myFiles.push(res.file);
        });
        $timeout(function(){
            $(".btnTooltip").tooltip();
        }, 500);
    });

    $scope.deleteFile               =   function(file, $index){
        if(confirm("Are you sure you want to do this? This action can not be undone.")){
            $scope.myFiles.splice($index, 1);

            $http({
                method: 'POST',
                url: 'actions/files/delete-file.php',
                data: file
            });
        }
    };

    $scope.addFileToChat            =   function(file){
        if(!$rootScope.last_cid && !$rootScope.pmUsername){
            return null;
        }

        $("#filesModal").modal('hide');

        $http({
            method: 'POST',
            url: 'actions/files/add-file-chat.php',
            data: {
                fid: file.id,
                cid: $rootScope.last_cid,
                username: $rootScope.pmUsername
            }
        });
    };
}]);