'use strict';

// This module requires fileDownload plugin
angular.module('download', [])

    // Download file api
    .factory('Download', ['$', 'session', '$http', 'noty', '$i18next', 'AppUtil', '$stateParams', 'configServer',
        function ($, session, $http, noty, $i18next, AppUtil, $stateParams, configServer) {

            var checkTimeDelay = 1000;
            var modalInstance = null;
            var timeoutId;

            function downloadFile(api, project_id, folder_id, pName, file_ids, file_version_id, type, email) {
                var data = {
                    email: email,
                    os: ''
                };
                var myJSON = JSON.stringify(data);
                var encodedString = window.btoa(myJSON.toString());
                var url = api + '?project_id=' + project_id + '&folder_id=' + folder_id + '&download_type=' + type + '&auth_token=' + session.getToken() + '&data=' + encodedString;

                if (file_version_id) {
                    url += '&file_version=' + file_version_id;
                }

                $.fileDownload(url, {httpMethod: 'GET'}).done(function () {

                    // Success download

                }).fail(function () {

                    // Fail to download

                }); // we need this plugin to create iframe download file
            }

            function downloadFileFromShareLink(api, project_id, pName, file_ids, file_version_id, type, printable, email) {
                var data = {
                    email: email,
                    os: ''
                };
                var myJSON = JSON.stringify(data);
                var encodedString = window.btoa(myJSON.toString());
                var url = api + '?project_id=' + project_id + '&download_type=' + type + '&auth_token=' + session.getToken() + "&printable=" + printable + "&link_id=" + $stateParams.link_id + '&data=' + encodedString;;

                if (file_version_id) {
                    url += '&file_version=' + file_version_id;
                }

                $.fileDownload(url, {httpMethod: 'GET'}).done(function () {

                    // Success download

                }).fail(function () {

                    // Fail to download

                }); // we need this plugin to create iframe download file
            }

            function checkQueueDownloadFolder(queue_id) {
                var pData = {
                    'queue_id': queue_id,
                    'auth_token': session.getToken()
                };
                var url = configServer.BACKEND_API_URL + 'api/download/folders/status' + '?' + $.param(pData);
                $http.get(url)
                    .then(function (response) {
                        var queueStatus = response.data.data.status;
                        switch (queueStatus) {
                            case 0: // queue pending
                            case 1: // queue make folder structure
                            case 2: // queue zipping files

                                // schedule check queue result
                                // still waiting download
                                if (modalInstance !== null) {
                                    timeoutId = setTimeout(function () {
                                        checkQueueDownloadFolder(queue_id);
                                    }, checkTimeDelay);
                                }
                                break;

                            case 3: // queue completed

                                // still waiting download
                                if (modalInstance !== null) {
                                    modalInstance.close();

                                    // call API download file
                                    var url = configServer.BACKEND_API_URL + 'api/download/folders/queue/' + queue_id + '?auth_token=' + session.getToken();
                                    $.fileDownload(url, {httpMethod: 'GET'}).done(function () {

                                        // Success download

                                    }).fail(function () {

                                        // Fail to download

                                    }); // we need this plugin to create iframe download file
                                }
                                break;

                            case 4: // queue error

                                // close popup
                                if (modalInstance !== null) {
                                    modalInstance.close();
                                }

                                // show error message
                                noty({
                                    text: $i18next('sever_errors.400'),
                                    type: 'error',
                                    theme: 'bootstrapTheme',
                                    layout: 'topCenter',
                                    timeout: 3000
                                });
                                break;
                        }

                    }, function () {
                        // show message error
                    });
            }

            return {

                // Nice font
                doDownloadFile: function (project_id, folder_id, file_ids, asZip, file_version_id, printable, email) {

                    // Check valid param
                    if (typeof file_ids === 'undefined' || typeof project_id === 'undefined')

                        return;

                    var type = (asZip) ? 3 : 1;// 3: zip, 1:normal

                    var folder_id = (folder_id) ? folder_id : "0"

                    var pName = (asZip) ? 'file_ids' : 'file_id';

                    // download multi files without zipping
                    var ids = file_ids.split(",");
                    // foreach
                    $.each(ids, function (index, id) {
                        var api = configServer.BACKEND_API_URL + 'api/download/files/' + id;
                        downloadFile(api, project_id, folder_id, pName, id, file_version_id, type, email);
                    });
                },

                // do download from share link
                doDownloadFileFromShareLink: function (project_id, file_ids, asZip, file_version_id, printable, link_id, email) {

                    // Check valid param
                    if (typeof file_ids === 'undefined' || typeof project_id === 'undefined')

                        return;

                    var type = (asZip) ? 3 : 1;// 3: zip, 1:normal

                    var pName = (asZip) ? 'file_ids' : 'file_id';

                    // download multi files without zipping
                    var ids = file_ids.split(",");

                    // foreach
                    $.each(ids, function (index, id) {
                        var api = configServer.BACKEND_API_URL + 'api/download/files/' + id + '/share';
                        downloadFileFromShareLink(api, project_id, pName, id, file_version_id, type, printable, email);

                    });
                },

                doDownloadAsZip: function (project_id, file_ids) {

                    var pData = {
                        'project_id': project_id,
                        'auth_token': session.getToken()
                    };
                    var url = configServer.BACKEND_API_URL + 'api/download/folders/' + file_ids + '?' + $.param(pData);
                    // show popup
                    modalInstance = AppUtil.confirm({
                        title: $i18next("message.download_zip.title_folder"),
                        message: $i18next("message.download_zip.content"),
                        closable: false,
                        buttons: [{
                            label: $i18next("button.cancel"),
                            cssClass: 'btn btn-warning',
                            action: function (dialog) {
                                dialog.close();
                                // clear current timeout
                                clearTimeout(timeoutId);
                                modalInstance = null;
                            }
                        }]
                    });
                    $http.get(url).then(function successCallback(response) {

                        // show message error
                        if (response.data.status !== 200) {
                            noty({
                                text: $i18next('sever_errors.' + response.data.status),
                                type: 'error',
                                theme: 'bootstrapTheme',
                                layout: 'topCenter',
                                timeout: 3000
                            });
                            modalInstance.close();
                        } else {
                            // get queue id
                            var queue_id = response.data.data.queue_id;
                            // schedule check queue result
                            setTimeout(function () {
                                checkQueueDownloadFolder(queue_id);
                            }, checkTimeDelay);

                        }

                    }, function () {
                        // show message error
                        // noty({
                        //     text: $i18next('sever_errors.400'),
                        //     type: 'error',
                        //     theme: 'bootstrapTheme',
                        //     layout: 'topCenter',
                        //     timeout: 3000
                        // });
                    });
                },

                downloadOne: function (project_id, file_id) {

                    var param = {
                        auth_token: session.getToken(),
                        project_id: project_id
                    };
                    var url = configServer.BACKEND_API_URL + 'api/download/files/' + file_id + '/printer' + '?' + $.param(param);

                    $.fileDownload(url, {httpMethod: 'get'});
                },

                downloadReceipt: function (auth_token, payment_info_id, company_id, team_id) {
                    var param = {
                        auth_token: auth_token,
                        company_id: company_id,
                        team_id: team_id,
                    };

                    var url = configServer.BACKEND_API_URL + 'api/download/teams/receipts/' + payment_info_id + '?' + $.param(param);

                    $.fileDownload(url, {httpMethod: 'GET'});
                },
                doDownloadZipWithPassword: function (params) {


                    var url = configServer.BACKEND_API_URL + 'api/download/files/zip?' + $.param(params);
                    $http.get(url).then(function successCallback(response) {

                        // show message error
                        if (response.data.status !== 200) {
                            noty({
                                text: $i18next('sever_errors.' + response.data.status),
                                type: 'error',
                                theme: 'bootstrapTheme',
                                layout: 'topCenter',
                                timeout: 3000
                            });
                        } else {
                            // get queue id
                            var queue_id = response.data.data.queue_id;
                            // schedule check queue result
                            setTimeout(function () {
                                checkQueueDownloadFolder(queue_id);
                            }, checkTimeDelay);

                            // show popup
                            modalInstance = AppUtil.confirm({
                                title: $i18next("message.download_zip.title"),
                                message: $i18next("message.download_zip.content_download"),
                                closable: false,
                                buttons: [{
                                    label: $i18next("button.cancel"),
                                    cssClass: 'btn btn-warning',
                                    action: function (dialog) {
                                        dialog.close();
                                        // clear current timeout
                                        clearTimeout(timeoutId);
                                        modalInstance = null;
                                    }
                                }]
                            });
                        }

                    }, function () {

                    });
                },

                downloadFileFromShareLinkNonDRM: function(project_id, file_id, link_id, email) {
                var url = configServer.BACKEND_API_URL + 'api/download/files/non-drm' + '?file_id=' + file_id + '&project_id=' + project_id + '&link_id=' + link_id+ '&email=' + window.btoa(email);


                $.fileDownload(url, {httpMethod: 'GET'}).done(function () {

                    // Success download

                }).fail(function () {

                    // Fail to download

                }); // we need this plugin to create iframe download file
            }

            };
        }]);


