(function() {
    'use strict';

    angular
        .module('app.contribute')
        .controller('ContributeController', ContributeController);

    function ContributeController($timeout, Upload) {
        //console.log("ContributeController called.");
        var vm = this;
        vm.fileDropped = false;
        vm.success = false;
        vm.error = false;
        vm.max = 100;

        vm.dropped = function(file) {
            vm.dynamic = 0;
            if (file[0]) {
                var tipo = file[0].type;
                if (!tipo.startsWith("image")) {
                    vm.error = true;
                    vm.success = false;
                    vm.fileDropped = false;
                    vm.errormessage = "The file must have a valid image format!";
                } else {
                    vm.error = false;
                    vm.fileDropped = true;
                }
            }
        };

        // upload on file select or drop
        vm.upload = function(file) {
            Upload.upload({
                url: '/api/upload',
                data: {
                    file: file
                }
            }).then(function(resp) {
                vm.success = true;
                vm.logo = null;
                vm.fileDropped = false;
            }, function(resp) {
                vm.error = true;
                vm.success = false;
                vm.fileDropped = false;
                vm.errormessage = "There was an API error!";
                console.log('Error status: ' + resp.status);
            }, function(evt) {
                vm.fileDropped = false;
                vm.dynamic = parseInt(100.0 * evt.loaded / evt.total);
            });

        };

    }
})();
