app.controller("documentosController", function ($scope, $modal, $http, $upload,dataService, documentosFactory, notificationFactory) {
    $scope.fornecedores = [];



    $scope.carregarDocumentos = function (item) {
        if (item == null)
            return;
        var getSuccessCallback = function (data, status) {

            $scope.documentos = data;

        };


        var errorCallback = function (data, status, headers, config) {
            notificationFactory.error(data);
        };

        documentosFactory.getDocumentos(item).success(getSuccessCallback).error(errorCallback);
    };

    $scope.downloadFicheiro = function (item) {
        if (item == null)
        {
            notificationFactory.error("Seleccione um Documento");
            return;
        }
        
        window.open("../api/downloaddoc/" + item.Pk_Documento + "/?tk=" + sessionStorage.getItem("CibeAtk"));
    };

    $scope.getFicheiro = function (item) {
        if (item == null)
            return;
        
        var getSuccessCallback = function (data, status) {
            //console.log(data);
            //$("#frm").attr('src', data.path);
            //var strMimeType = "application/pdf";
            ////data = data.replace('"', '');
            //var d = "data:" + strMimeType + ";base64," + encodeURI(data);
            ////console.log(d);
            //window.open(d);
            //$scope.SaveToDisk("views/white.html","Documento de Teste.pdf");
            //var blob = new Blob([data], {  });
            //var objectUrl = URL.createObjectURL(blob);
            //window.open(objectUrl);
        };


        var errorCallback = function (data, status, headers, config) {
            notificationFactory.error(data);
        };

        documentosFactory.getFicheiro(item.Pk_Documento).success(getSuccessCallback).error(errorCallback);
    };

    


    $scope.apagarDocumento = function (elem) {
        if (elem == null)
            return;


        var successCallback = function (data, status, headers, config) {

            
            notificationFactory.success(data);
            var arr = $scope.documentos;
            for (i = 0; i < arr.length; i++) {
                if (arr[i] == elem) {
                    arr.splice(i, 1);

                    break;

                }
            }

            $scope.selectedRow = null
        };


        var errorCallback = function (data, status, headers, config) {
            notificationFactory.error(data);
        };

        documentosFactory.deleteDocumento(elem).success(successCallback).error(errorCallback);
    };

    $scope.selDocumento = function (row) {
        $scope.selectedRow = row;

    };

    

    $scope.confirmarApagarDocumento = function (row) {
        if (row == null)
            return;

        var modalInstance = $modal.open(
        {

            templateUrl: 'views/modalConfirmarApagar.html?v=' + new Date(),
            controller: 'modalController',
            resolve: {

                items: function () { return row; },

                //  isNew: false
            }
        });

        modalInstance.result.then(function (item) {

            $scope.apagarDocumento(item);

        }, function () {

        });

    };

    //Upload
    $scope.myDocFile = "";

    $scope.onFileSelect = function ($files, info) {
        //$files: an array of files selected, each file has name, size, and type.
        var tipo = info.tipodoc;
        var informacao = {};
      
        if (tipo == "Aquisicao")
        {
            informacao = {
                tipo: "Aquisicao",
                id: info.Aquisicao.Pk_InventarioAquisicao
            };
        }
        else if (tipo == "Abate")
        {
            informacao = {
                tipo: "Abate",
                id: info.Abate.Pk_InventarioAbate
            };
        }
        else if (tipo == "Alteracao")
        {
            informacao = {
                tipo: "Alteracao",
                id: info.Pk_InventarioAlteracao
            };
        }
        
      
        for (var i = 0; i < $files.length; i++) {
            var $file = $files[i];
            (function (index) {
                $upload.upload({
                    url: "../api/documentos/" , // webapi url
                    method: "POST",
                    
                    data: informacao,
                    
                    file: $file
                }).progress(function (evt) {
                    // get upload percentage
                    $scope.uploadprogress = parseInt(100.0 * evt.loaded / evt.total);


                    //console.log('percent: ' + $scope.uploadprogress);
                }).success(function (data, status, headers, config) {

                    //console.log(data);
                    data = data.toString();
                    if (data.substr(0, 5) != "Erro:")
                    {
                        notificationFactory.success(data);
                        $scope.carregarDocumentos(info);
                    }
                        
                    else
                        notificationFactory.error(data);

                    
                    

                }).error(function (data, status, headers, config) {
                    // file failed to upload
                    //console.log(data);
                    notificationFactory.error(data);
                });

            })(i);
        }
    };

    /*$scope.atribuirDocumento = function (row, cadastro) {
        if (row == null || cadastro == null)
            return;
        $scope.selectItem(row)
        cadastro.NomeFornecedor = row.Nome;
        cadastro.Fk_Fornecedor = row.Pk_Fornecedor;
    };

    $scope.ativarLinha = function (row, cadastro) {
        if (row == null || cadastro == null)
            return;
        if (row.Pk_Fornecedor == cadastro.Fk_Fornecedor) {
            $scope.selectItem(row)
            cadastro.NomeFornecedor = row.Nome;
            cadastro.Fk_Fornecedor = row.Pk_Fornecedor;
        }


    };*/
        

});