'use strict';

angular.module('myEmail', []).controller('MyEmailCtrl', [
  '$scope',
  '$state',
  '$timeout',
  'Util',
  'AppConfig',
  '$uibModal',
  'session',
  '$http',
  'moment',
  '$q',
  'ViewerSupportType',
  'ViewerUrl',
  '$sce',
  '$filter',
  'configServer',
  '$stateParams',
  '$rootScope',
  function (
    $scope,
    $state,
    $timeout,
    Util,
    AppConfig,
    $uibModal,
    session,
    $http,
    moment,
    $q,
    ViewerSupportType,
    ViewerUrl,
    $sce,
    $filter,
    configServer,
    $stateParams,
    $rootScope
  ) {
    $scope.currentUser = session.getUser();
    $scope.isSort = false;
    $scope.openMenu = {
      first: false,
      second: false,
    };
    $scope.pagination = {
      currentPage: 1,
    };
    $scope.sortField = 'createdDate';
    $scope.selected = [];
    $scope.filePath = '';
    $scope.searchString = { key: '' };

    $scope.filterOptions = [
      { id: 1, name: Util.translate('MY_EMAIL.ACTIVE'), value: true },
      { id: 2, name: Util.translate('MY_EMAIL.ALL'), value: false },
    ];

    $scope.pageOptions = [
      { id: 1, name: '5', value: 5 },
      { id: 2, name: '10', value: 10 },
      { id: 3, name: '20', value: 20 },
      { id: 4, name: '50', value: 50 },
    ];
    $scope.folderId = $stateParams.folder_id;
    $scope.pageSize = $scope.pageOptions[1];
    $scope.active = { selected: $scope.filterOptions[0] };

    $scope.downloadSelectedItems = function () {
      $scope.selected.forEach(function (item) {
        var isZipFile = item.content_type && item.content_type.toLowerCase().endsWith('zip');

        if (isZipFile) {
          $scope.openModalDownloadOrUnzipAndSaveFolder(item);
        } else {
          $scope.doDownload(item, $scope.projectId, $scope.currentUser.mail_address);
        }
        // $scope.doDownload(item, $scope.projectId, $scope.currentUser.mail_address);
      });
    };

    $scope.menuOptions = function (item) {
      if (!!item.openMenu && item.openMenu === true) {
        // On mouse-over, execute myFunction
        setTimeout(function () {
          document.getElementById('tog' + item.id).click();
        }, 500);
      }
      if ($scope.openMenu.first === true) {
        // On mouse-over, execute myFunction
        setTimeout(function () {
          document.getElementById('moreOptionId1').click();
        }, 500);
      }
      if ($scope.openMenu.second === true) {
        // On mouse-over, execute myFunction
        setTimeout(function () {
          document.getElementById('moreOptionId2').click();
        }, 500);
      }

      console.log('$scope.selected', $scope.selected);

      if ($scope.selected.length !== 0) {
        if (_.intersectionBy($scope.selected, 'status').length !== 1) {
          return [];
        }

        if ($scope.selected[0].status === 1) {
          if ($scope.selected.length === 1 && $scope.selected[0].folder === false) {
            //if one file and active
            return [
              {
                text:
                  '<i class="fa fas fa-download pr-2" aria-hidden="true"></i>' +
                  Util.translate('CONTEXT_MENU.DOWNLOAD'),
                click: function ($itemScope, $event, modelValue, text, $li) {
                  $scope.selected.forEach(function (item) {
                    var isZipFile =
                      item.content_type && item.content_type.toLowerCase().endsWith('zip');

                    if (isZipFile) {
                      $scope.openModalDownloadOrUnzipAndSaveFolder(item);
                    } else {
                      $scope.doDownload(item, $scope.projectId, $scope.currentUser.mail_address);
                    }
                  });
                },
              },
              {
                text:
                  '<i class="fas fa-eye pr-04rem" aria-hidden="true"></i>' +
                  Util.translate('CONTEXT_MENU.VIEW_ONLINE'),
                click: function ($itemScope, $event, modelValue, text, $li) {
                  $scope.showViewOnline($scope.selected[0], $scope.currentUser.mail_address);
                },
              },
              {
                text:
                  '<i class="fas fa-chart-bar pr-2" aria-hidden="true"></i>' +
                  Util.translate('CONTEXT_MENU.VIEW_REPORT'),
                click: function ($itemScope, $event, modelValue, text, $li) {
                  $scope.viewReport($scope.selected[0], $scope.projectId);
                },
              },
              {
                text:
                  '<i class="fas fa-trash pr-06rem" aria-hidden="true"></i>' +
                  Util.translate('CONTEXT_MENU.REMOVE'),
                click: function ($itemScope, $event, modelValue, text, $li) {
                  $scope.removeSubject($scope.selected, $scope.projectId);
                },
              },
            ];
          } else if (
            $scope.selected.length > 1 &&
            $scope.selected[0].folder === false &&
            _.every($scope.selected, ['folder', false])
          ) {
            //if multiple file and active
            return [
              {
                text:
                  '<i class="fa fas fa-download pr-2" aria-hidden="true"></i>' +
                  Util.translate('CONTEXT_MENU.DOWNLOAD'),
                click: function ($itemScope, $event, modelValue, text, $li) {
                  $scope.selected.forEach(function (item) {
                    $scope.doDownload(item, $scope.projectId, $scope.currentUser.mail_address);
                  });
                },
              },
              {
                text:
                  '<i class="fas fa-trash pr-06rem" aria-hidden="true"></i>' +
                  Util.translate('CONTEXT_MENU.REMOVE'),
                click: function ($itemScope, $event, modelValue, text, $li) {
                  $scope.removeSubject($scope.selected, $scope.projectId);
                },
              },
            ];
          } else {
            // if selected contain folder
            return [
              {
                text:
                  '<i class="fas fa-trash pr-06rem" aria-hidden="true"></i>' +
                  Util.translate('CONTEXT_MENU.REMOVE'),
                click: function ($itemScope, $event, modelValue, text, $li) {
                  $scope.removeSubject($scope.selected, $scope.projectId);
                },
              },
            ];
          }
        } else {
          return [
            {
              text:
                '<i class="fas fa-trash-restore-alt pr-2" aria-hidden="true"></i>' +
                Util.translate('CONTEXT_MENU.RESTORE'),
              click: function ($itemScope, $event, modelValue, text, $li) {
                $scope.restoreItems($scope.selected, $scope.projectId);
              },
            },
            {
              text:
                '<i class="fas fa-trash pr-2" aria-hidden="true"></i>' +
                Util.translate('CONTEXT_MENU.REMOVE_FOREVER'),
              click: function ($itemScope, $event, modelValue, text, $li) {
                $scope.deleteForeverSubjects($scope.selected, $scope.projectId);
              },
            },
          ];
        }
      } else {
        return [
          {
            text: Util.translate('CONTEXT_MENU.DEFAULT'),
          },
        ];
      }
    };

    var param = {
      active: $scope.active.selected.value,
      asc_sort: false,
      length: 20,
      search_global: false,
      search_key: '',
      sort_field: 'modifiedDate',
      start: 1,
    };

    $scope.doSort = function (sortCase) {
      $scope.loadProjectItems(sortCase);
    };

    $scope.pageChanged = function (opt, current) {
      $scope.pageSize = opt;
      $scope.pagination.currentPage = current;
      $scope.loadProjectItems();
    };

    $scope.doSearch = function () {
      $scope.pagination.currentPage = 1;
      $scope.loadProjectItems();
    };

    $scope.loadProject = function () {
      $scope.submitting = true;
      Util.createRequest(
        configServer.API_URL + '/projects/secure-mail',
        'GET',
        {},
        function (response) {
          var status = response.status;
          $scope.resultProject = response.data;
          if (status === 200) {
            if (response.data.length === 0) {
              $scope.filePath = '';
              // Util.createToast({className: 'danger', content: 'COMMON.PROJECT_MY_FILES_NOT_FOUND'});
            } else {
              $scope.myFileProjects = response.data[0];
              $scope.projectId = $scope.myFileProjects.project_id;
              $scope.loadProjectItems();
              $scope.drawFilePath();
            }
          } else {
            Util.createToast({ className: 'danger', content: 'SERVER_ERROR.' + status });
          }
          $scope.submitting = false;
        },
        function (error) {
          Util.createToast({
            className: 'danger',
            content: 'SERVER_ERROR.' + error.status,
          });
          $scope.submitting = false;
        }
      );
    };

    $scope.loadProject();

    $scope.changeActive = function (active) {
      $scope.active = active;
      $scope.loadProjectItems();
    };

    $scope.loadRelatedFolderInfos = function () {
      var folderList = $scope.items.filter(function (item) {
        return item.folder;
      });
      if (folderList.length > 0) {
        var params = {
          project_id: this.projectId,
          folder_ids: folderList
            .map(function (file) {
              return file.id;
            })
            .join(','),
        };
        Util.createRequest(
          configServer.API_URL + '/folders/related-info',
          'GET',
          params,
          function (response) {
            if (response.status === 200) {
              response.data.map(function (obj) {
                var index = $scope.items.findIndex(function (el) {
                  return el.id === obj.folder_id;
                });
                if (index !== -1) {
                  $scope.items[index].file_size = obj.number_file;
                  $scope.items[index].number_user = obj.number_user;
                  $scope.items[index].user_folder_role = obj.user_folder_role;
                }
              });
              console.log('', $scope.items);
            }
          },
          function (error) {
            Util.createToast({
              className: 'danger',
              content: 'SERVER_ERROR.' + error.status,
            });
          }
        );
      }
    };
    $scope.loadRelatedFileInfos = function () {
      var fileList = $scope.items.filter(function (item) {
        return !item.folder;
      });
      if (fileList.length > 0) {
        var params = {
          project_id: $scope.projectId,
          folder_id: $scope.folderId,
          file_ids: fileList
            .map(function (file) {
              return file.id;
            })
            .join(','),
        };
        Util.createRequest(
          configServer.API_URL + '/files/related-info',
          'GET',
          params,
          function (response) {
            if (response.status === 200) {
              response.data.map(function (obj) {
                var index = $scope.items.findIndex(function (el) {
                  return el.id === obj.file_id;
                });
                if (index !== -1) {
                  $scope.items[index].parent_folder_id = obj.parent_folder_id;
                  $scope.items[index].version = obj.version;
                  $scope.items[index].total_version = obj.total_version;
                  $scope.items[index].user_file_role = obj.user_file_role;
                }
              });
            }
          },
          function (error) {
            Util.createToast({
              className: 'danger',
              content: 'SERVER_ERROR.' + error.status,
            });
          }
        );
      }
    };

    $scope.loadProjectItems = function (sortCase) {
      $scope.submitting = true;
      if (sortCase) {
        if ($scope.sortField === sortCase) {
          $scope.isSort = !$scope.isSort;
        } else {
          $scope.isSort = true;
        }
        param.asc_sort = $scope.isSort;
        param.sort_field = sortCase;
        $scope.sortField = sortCase;
      }
      param.active = $scope.active.selected.value;
      param.project_id = $scope.projectId;
      param.search_key = $scope.searchString.key;
      param.page_number = $scope.pagination.currentPage;
      param.length = $scope.pageSize.value;
      param.start = $scope.pageSize.value * ($scope.pagination.currentPage - 1) + 1;
      // reset state
      Util.createRequest(
        configServer.API_URL + '/folders/' + $scope.folderId + '/items',
        'GET',
        param,
        function (response) {
          $scope.items = [];
          var status = response.status;
          if (status === 200) {
            $scope.items = response.data.file_info;
            $scope.loadRelatedFolderInfos();
            $scope.loadRelatedFileInfos();
            $scope.totalItems = response.data.total_result;
            $scope.totalPage = Math.ceil($scope.totalItems / $scope.pageSize.value);

            $scope.items.forEach(function (item) {
              item._selected = false;
            });

            //bind check box again
            if ($scope.selected.length > 0) {
              $scope.items.forEach(function (result) {
                $scope.selected.forEach(function (selected) {
                  if (result.id === selected.id) {
                    result._selected = true;
                  }
                });
              });
            }
          } else {
            Util.createToast({ className: 'danger', content: 'SERVER_ERROR.' + status });
          }
          $scope.submitting = false;
        },
        function (error) {
          $scope.submitting = false;
          Util.createToast({ className: 'danger', content: 'SERVER_ERROR.' + error.status });
        }
      );
    };

    // $scope.loadProjectItems = function (sortCase) {
    //     $scope.submitting = true;
    //     if (sortCase) {
    //         if ($scope.sortField === sortCase) {
    //             $scope.isSort = !$scope.isSort;
    //         } else {
    //             $scope.isSort = true;
    //         }
    //         param.asc_sort = $scope.isSort;
    //         param.sort_field = sortCase;
    //         $scope.sortField = sortCase;
    //     }
    //     param.active = $scope.active.selected.value;
    //     param.project_id = $scope.projectId;
    //     param.search_key = $scope.searchString.key;
    //     param.page_number = $scope.pagination.currentPage;
    //     param.length = $scope.pageSize.value;
    //     param.start = ($scope.pageSize.value * ($scope.pagination.currentPage - 1)) + 1;
    //     // reset state
    //     Util.createRequest(configServer.API_URL + "/folders/" + $scope.folderId + "/items", "GET", param, function (response) {
    //         $scope.items = [];
    //         var status = response.status;
    //         if (status === 200) {
    //             $scope.items = response.data.file_info;
    //             $scope.totalItems = response.data.total_result;
    //             $scope.totalPage = Math.ceil($scope.totalItems / $scope.pageSize.value);

    //             $scope.items.forEach(function (item) {
    //                 item._selected = false;
    //             });

    //             //bind check box again
    //             if ($scope.selected.length > 0) {

    //                 $scope.items.forEach(function (result) {
    //                     $scope.selected.forEach(function (selected) {
    //                         if (result.id === selected.id) {
    //                             result._selected = true;
    //                         }
    //                     });
    //                 });
    //             }
    //         } else {
    //             Util.createToast({className: 'danger', content: 'SERVER_ERROR.' + status});
    //         }
    //         $scope.submitting = false;
    //     }, function (error) {
    //         $scope.submitting = false;
    //         Util.createToast({className: 'danger', content: 'SERVER_ERROR.' + error.status});
    //     });
    // };

    $scope.toggleSelected = function (clickEvent, obj) {
      if (angular.isObject(obj) && obj.id) {
        if (clickEvent.ctrlKey) {
          if ($scope.selected.length > 0 && $scope.selected[0].status !== obj.status) {
            return;
          }
          if ($scope.selected.length > 0 && $scope.selected[0].folder !== obj.folder) {
            return;
          }
          var index = _.findIndex($scope.selected, { id: obj.id });
          if (index > -1) {
            $scope.selected.splice(index, 1);
            obj._selected = false;
          } else {
            $scope.selected.push(obj);
            obj._selected = true;
          }
        } else if (clickEvent.shiftKey) {
          if ($scope.selected.length > 0 && $scope.selected[0].status !== obj.status) {
            return;
          }
          if ($scope.selected.length > 0 && $scope.selected[0].folder !== obj.folder) {
            return;
          }
          $scope.items.forEach(function (temp) {
            temp._selected = false;
          });
          if ($scope.selected.length === 0) {
            $scope.selected = [];
            obj._selected = true;
            $scope.selected.push(obj);
          } else {
            $scope.selected = [];

            if ($scope.currentSelectedItem.id === obj.id) {
              obj._selected = true;
              $scope.selected.push(obj);
            } else {
              var index = _.findIndex($scope.items, { id: obj.id });
              var current = _.findIndex($scope.items, { id: $scope.currentSelectedItem.id });

              if (current < index) {
                for (var i = current; i <= index; i++) {
                  $scope.items[i]._selected = true;
                  $scope.selected.push($scope.items[i]);
                }
              } else {
                for (var i = index; i <= current; i++) {
                  $scope.items[i]._selected = true;
                  $scope.selected.push($scope.items[i]);
                }
              }
            }
          }
        } else {
          $scope.items.forEach(function (temp) {
            temp._selected = false;
          });
          $scope.selected = [];
          obj._selected = true;
          $scope.selected.push(obj);
        }
        //set current selected
        if (obj._selected) {
          $scope.currentSelectedItem = obj;
        }
      }
    };

    //this function to fix the right click menu with empty select
    $scope.whichButton = function (event, item) {
      if (event.button === 2) {
        if ($scope.selected.length === 0) {
          $scope.items.forEach(function (temp) {
            temp._selected = false;
          });
          $scope.selected = [];

          item._selected = true;
          $scope.selected.push(item);
        } else {
          var isSelected = false;
          $scope.selected.forEach(function (temp) {
            if (item.id === temp.id) {
              isSelected = true;
            }
          });
          if (!isSelected) {
            $scope.items.forEach(function (temp) {
              temp._selected = false;
            });
            $scope.selected = [];

            item._selected = true;
            $scope.selected.push(item);
          }
        }
      }
    };

    $scope.removeSubject = function (list, projectId) {
      //show confirm delete
      return $uibModal
        .open({
          templateUrl: 'components/modal-template/confirm_delete_modal.html',
          size: 'md',
          controller: [
            '$scope',
            '$rootScope',
            '$uibModalInstance',
            '$translate',
            '$cookies',
            'configServer',
            function ($scope, $rootScope, $uibModalInstance, $translate, $cookies, configServer) {
              $translate([
                'COMMON.BUTTON_CANCEL',
                'COMMON.BUTTON_OK',
                'MY_EMAIL.DELETE_SUBJECT_MSG',
                'MY_EMAIL.DELETE_SUBJECT_TITLE',
              ]).then(function (translations) {
                $scope.opts = {
                  title: translations['MY_EMAIL.DELETE_SUBJECT_TITLE'],
                  message: translations['MY_EMAIL.DELETE_SUBJECT_MSG'],
                  lblAccept: translations['COMMON.BUTTON_OK'],
                  lblDismiss: translations['COMMON.BUTTON_CANCEL'],
                };
                $scope.onClose = function () {
                  $uibModalInstance.close();
                };

                $scope.onAccept = function () {
                  //delete list
                  $scope.submitting = true;
                  var reqs = [];
                  var i = 0;
                  var allSuccess;
                  var error;
                  var paramRemove;
                  while (i < list.length) {
                    if (list[i].status !== 1) {
                      i++;
                      continue;
                    }
                    paramRemove = {
                      project_id: projectId,
                    };
                    if (list[i].folder === true) {
                      paramRemove.folder_id = list[i].id;
                    } else {
                      paramRemove.file_id = list[i].id;
                    }
                    i++;
                    reqs.push(
                      Util.createRequest(
                        configServer.API_URL + '/trash/items',
                        'DELETE',
                        paramRemove,
                        function (response) {
                          allSuccess = response.status;
                        }
                      )
                    );
                  }

                  if (reqs.length > 0) {
                    // Post all reqs
                    $q.all(reqs).then(function (data) {
                      if (allSuccess === 200) {
                        //create tooast success
                        Util.createToast({
                          className: 'success',
                          content: 'COMMON.MESSAGE.DELETE_SUCCESS_MESSAGE',
                        });
                      } else if (allSuccess !== 200 && allSuccess !== undefined) {
                        //toast fail
                        Util.createToast({
                          className: 'danger',
                          content: 'SERVER_ERROR.' + allSuccess,
                        });
                      }
                      $rootScope.$broadcast('load_list_items', 'loadList');
                      $uibModalInstance.close();
                    });
                  }
                  $scope.submitting = false;
                };
              });
            },
          ],
        })
        .result.catch(function (resp) {
          if (['cancel', 'backdrop click', 'escape key press'].indexOf(resp) === -1) {
            throw resp;
          }
        });
    };

    $scope.$on('load_list_items', loadListProjectItems);

    function loadListProjectItems(event, value) {
      $scope.selected = [];
      $scope.loadProjectItems();
    }

    $scope.deleteForeverSubjects = function (list, projectId) {
      //show confirm delete
      return $uibModal
        .open({
          templateUrl: 'components/modal-template/confirm_delete_modal.html',
          size: 'md',
          controller: [
            '$scope',
            '$rootScope',
            '$uibModalInstance',
            '$translate',
            '$cookies',
            'configServer',
            function ($scope, $rootScope, $uibModalInstance, $translate, $cookies, configServer) {
              $translate([
                'COMMON.BUTTON_CANCEL',
                'COMMON.BUTTON_OK',
                'MY_EMAIL.DELETE_FOREVER_SUBJECT_TITLE',
                'MY_EMAIL.DELETE_FOREVER_SUBJECT_MSG',
              ]).then(function (translations) {
                $scope.opts = {
                  title: translations['MY_EMAIL.DELETE_FOREVER_SUBJECT_TITLE'],
                  message: translations['MY_EMAIL.DELETE_FOREVER_SUBJECT_MSG'],
                  lblAccept: translations['COMMON.BUTTON_OK'],
                  lblDismiss: translations['COMMON.BUTTON_CANCEL'],
                };
                $scope.onClose = function () {
                  $uibModalInstance.close();
                };
                $scope.onAccept = function () {
                  //delete list
                  $scope.submitting = true;
                  var reqs = [];
                  var i = 0;
                  var allSuccess;
                  var paramRemove;
                  while (i < list.length) {
                    if (list[i].status === 1) {
                      i++;
                      continue;
                    }
                    paramRemove = {
                      project_id: projectId,
                    };
                    if (list[i].folder === true) {
                      paramRemove.folder_id = list[i].id;
                    } else {
                      paramRemove.file_id = list[i].id;
                    }
                    i++;

                    reqs.push(
                      Util.createRequest(
                        configServer.API_URL + '/trash/items/physical',
                        'DELETE',
                        paramRemove,
                        function (response) {
                          allSuccess = response.status;
                        }
                      )
                    );
                  }

                  if (reqs.length > 0) {
                    // Post all reqs
                    $q.all(reqs).then(function (data) {
                      if (allSuccess === 200) {
                        //create tooast success
                        Util.createToast({
                          className: 'success',
                          content: 'COMMON.MESSAGE.DELETE_SUCCESS_MESSAGE',
                        });
                      } else if (allSuccess !== 200 && allSuccess !== undefined) {
                        //toast fail
                        Util.createToast({
                          className: 'danger',
                          content: 'SERVER_ERROR.' + allSuccess,
                        });
                      }
                      $rootScope.$broadcast('load_list_items', 'loadList');
                      $uibModalInstance.close();
                    });
                  }
                  $scope.submitting = false;
                };
              });
            },
          ],
        })
        .result.catch(function (resp) {
          if (['cancel', 'backdrop click', 'escape key press'].indexOf(resp) === -1) {
            throw resp;
          }
        });
    };

    $scope.restoreItems = function (list, projectId) {
      //show confirm delete
      return $uibModal
        .open({
          templateUrl: 'components/modal-template/confirm_delete_modal.html',
          size: 'md',
          controller: [
            '$scope',
            '$rootScope',
            '$uibModalInstance',
            '$translate',
            '$cookies',
            'configServer',
            function ($scope, $rootScope, $uibModalInstance, $translate, $cookies, configServer) {
              $translate([
                'COMMON.BUTTON_CANCEL',
                'COMMON.BUTTON_OK',
                'MY_EMAIL.RESTORE_SUBJECT_TITLE',
                'MY_EMAIL.RESTORE_SUBJECT_MSG',
              ]).then(function (translations) {
                $scope.opts = {
                  title: translations['MY_EMAIL.RESTORE_SUBJECT_TITLE'],
                  message: translations['MY_EMAIL.RESTORE_SUBJECT_MSG'],
                  lblAccept: translations['COMMON.BUTTON_OK'],
                  lblDismiss: translations['COMMON.BUTTON_CANCEL'],
                };
                $scope.onClose = function () {
                  $uibModalInstance.close();
                };
                $scope.onAccept = function () {
                  //delete list
                  $scope.submitting = true;
                  var reqs = [];
                  var i = 0;
                  var allSuccess;
                  var paramRemove;
                  while (i < list.length) {
                    if (list[i].status === 1) {
                      i++;
                      continue;
                    }
                    paramRemove = {
                      project_id: projectId,
                    };
                    if (list[i].folder === true) {
                      paramRemove.folder_id = list[i].id;
                    } else {
                      paramRemove.file_id = list[i].id;
                    }
                    i++;

                    reqs.push(
                      Util.createRequest(
                        configServer.API_URL + '/trash/items/restore',
                        'PUT',
                        paramRemove,
                        function (response) {
                          allSuccess = response.status;
                        }
                      )
                    );
                  }

                  if (reqs.length > 0) {
                    // Post all reqs
                    $q.all(reqs).then(function (data) {
                      if (allSuccess === 200) {
                        //create tooast success
                        Util.createToast({
                          className: 'success',
                          content: 'COMMON.MESSAGE.RESTORE_SUCCESS_MESSAGE',
                        });
                      } else if (allSuccess !== 200 && allSuccess !== undefined) {
                        //toast fail
                        Util.createToast({
                          className: 'danger',
                          content: 'SERVER_ERROR.' + allSuccess,
                        });
                      }
                      $rootScope.$broadcast('load_list_items', 'loadList');
                      $uibModalInstance.close();
                    });
                  }
                  $scope.submitting = false;
                };
              });
            },
          ],
        })
        .result.catch(function (resp) {
          if (['cancel', 'backdrop click', 'escape key press'].indexOf(resp) === -1) {
            throw resp;
          }
        });
    };

    $scope.viewReport = function (item, projectId) {
      $state.go('trackingPage', {
        project_id: projectId,
        folder_id: item.parent_folder_id,
        file_id: item.id,
        file_type: item.is_encrypt,
      });
    };

    // Download ZIP file from server
    async function downloadZipFile(url) {
      const response = await fetch(url);
      if (!response.ok) {
        throw new Error('Unable to download ZIP file');
      }
      return await response.blob();
    }

    // Read contents of the ZIP file
    async function readZipContents(zipBlob) {
      const zip = await JSZip.loadAsync(zipBlob);
      const fileEntries = Object.values(zip.files).filter((entry) => !entry.dir);

      if (fileEntries.length === 0) {
        throw new Error('Empty ZIP file');
      }

      return { zip, fileEntries };
    }

    // Get target directory for extraction
    async function getTargetDirectory() {
      return await window.showDirectoryPicker({
        id: 'extractZip',
        mode: 'readwrite',
        startIn: 'downloads',
      });
    }

    // Create or open subdirectory in the target directory (optional)
    async function getOrCreateSubdirectory(dirHandle, pathParts) {
      let currentDirHandle = dirHandle;

      for (const part of pathParts) {
        if (!part) continue; // Skip empty elements

        try {
          // Create or open a subfolder
          currentDirHandle = await currentDirHandle.getDirectoryHandle(part, { create: true });
        } catch (err) {
          console.error('Error when create folder:', part, err);
        }
      }

      return currentDirHandle;
    }

    // Save a file to the directory
    async function saveFileToDirectory(dirHandle, fileName, content) {
      const fileHandle = await dirHandle.getFileHandle(fileName, { create: true });
      const writable = await fileHandle.createWritable();

      await writable.write(content);
      await writable.close();
    }

    // Process status update
    function updateProgress(processedCount, totalCount) {
      if (processedCount % 5 === 0 || processedCount === totalCount) {
        Util.createToast({
          className: 'info',
          content: 'Unzip ' + processedCount + ' / ' + totalCount + ' files',
        });
      }
    }

    $scope.openModalDownloadOrUnzipAndSaveFolder = function (file) {
      return $uibModal
        .open({
          templateUrl: 'components/modal-template/confirm_download_or_unzip_and_save_folder.html',
          size: 'md',
          resolve: {
            mailAddress: function () {
              return $scope.currentUser.mail_address;
            },
            projectId: function () {
              return $scope.projectId;
            },
            file: function () {
              return file;
            },
            downloadFunction: function () {
              return $scope.doDownload;
            },
          },
          controller: [
            '$scope',
            '$uibModalInstance',
            '$translate',
            'mailAddress',
            'projectId',
            'file',
            'downloadFunction',
            function (
              $scope,
              $uibModalInstance,
              $translate,
              mailAddress,
              projectId,
              file,
              downloadFunction
            ) {
              $translate([
                'VIEW_DOWNLOAD.CONFIRM_DOWNLOAD_OR_UNZIP_AND_SAVE_FOLDER_TITLE',
                'VIEW_DOWNLOAD.CONFIRM_DOWNLOAD_OR_UNZIP_AND_SAVE_FOLDER_MSG',
                'VIEW_DOWNLOAD.JUST_DOWNLOAD_BUTTON',
                'VIEW_DOWNLOAD.DOWNLOAD_AND_UNZIP_SAVE_BUTTON',
              ]).then(function (translations) {
                $scope.opts = {
                  title:
                    translations['VIEW_DOWNLOAD.CONFIRM_DOWNLOAD_OR_UNZIP_AND_SAVE_FOLDER_TITLE'],
                  message:
                    translations['VIEW_DOWNLOAD.CONFIRM_DOWNLOAD_OR_UNZIP_AND_SAVE_FOLDER_MSG'],
                  justDownloadLabel: translations['VIEW_DOWNLOAD.JUST_DOWNLOAD_BUTTON'],
                  downloadAndUnzipLabel:
                    translations['VIEW_DOWNLOAD.DOWNLOAD_AND_UNZIP_SAVE_BUTTON'],
                };
                $scope.onClose = function () {
                  $uibModalInstance.close();
                };

                $scope.onJustDownload = function () {
                  downloadFunction(file, projectId, mailAddress);
                  $uibModalInstance.close();
                };

                $scope.onUnzipAndSaveFolder = function () {
                  var isUnzip = true;
                  // Call getTargetDirectory() first to ensure user gesture
                  getTargetDirectory()
                    .then(function (dirHandle) {
                      // Call doDownload with dirHandle selected
                      downloadFunction(file, projectId, mailAddress, isUnzip, dirHandle);
                    })
                    .catch(function (error) {
                      console.error('Failed to select directory:', error);
                      Util.createToast({
                        className: 'warning',
                        content: Util.translate('MY_EMAIL.SELECT_DIRECTORY_ERROR'),
                      });
                    });
                  $uibModalInstance.close();
                };

                // close modal
                $scope.$on('close_modal', closeModal);

                function closeModal(event, value) {
                  $uibModalInstance.close();
                }
              });
            },
          ],
        })

        .result.catch(function (resp) {
          if (['cancel', 'backdrop click', 'escape key press'].indexOf(resp) === -1) {
            throw resp;
          }
        });
    };

    /**
     * Extracts a ZIP file from a provided URL and saves its contents to a user-selected directory.
     *
     * This function performs the following tasks:
     * 1. Downloads the ZIP file from the server using the Fetch API.
     * 2. Reads and parses the ZIP file contents using the JSZip library.
     * 3. Iterates through the files in the ZIP archive and maintains the folder structure.
     * 4. Prompts the user to select a target directory using the File System Access API.
     * 5. Creates necessary subdirectories in the target directory to match the ZIP file's structure.
     * 6. Saves each file to the appropriate location in the selected directory.
     * 7. Displays progress notifications during the extraction process.
     * 8. Shows a success message upon completion or an error message if the process fails.
     *
     * @param {string} url - The URL from which to download the ZIP file.
     * @param {FileSystemDirectoryHandle} dirHandle - The directory handle where the files will be extracted.
     * @returns {Promise<void>} - A promise that resolves when the extraction is complete.
     * @throws Will throw an error if any part of the process fails.
     *
     * @requires JSZip - A library for reading and writing ZIP files.
     * @requires File System Access API - A modern browser API for file system operations.
     */
    async function extractZipFileWithDirectory(url, dirHandle) {
      try {
        // Download the ZIP file from the provided URL
        const zipBlob = await downloadZipFile(url);

        // Read the ZIP file contents using JSZip
        const { zip, fileEntries } = await readZipContents(zipBlob);

        // Use the provided directory handle
        for (const entry of fileEntries) {
          try {
            // Convert the file content to an ArrayBuffer
            const content = await entry.async('arraybuffer');

            // Split the entry name into parts to handle subdirectories
            const pathParts = entry.name.split('/');
            const fileName = pathParts.pop();

            // Get or create the subdirectory in the target directory
            const targetDir = await getOrCreateSubdirectory(dirHandle, pathParts);

            // Save the file to the target directory
            await saveFileToDirectory(targetDir, fileName, content);
          } catch (error) {
            console.error('Error unzip file:', entry.name, error);
          }
        }
        $rootScope.$broadcast('close_popup');

        // Show completion message
        Util.createToast({
          className: 'success',
          content: Util.translate('MY_EMAIL.UNZIP_SUCCESS'),
        });
        console.log('Unzip completed successfully');
      } catch (error) {
        $rootScope.$broadcast('close_popup');
        console.error('Error extract zip function:', error);
        throw error; // Re-throw để caller có thể handle
      }
    }

    // Check if the browser supports File System Access API
    async function checkBrowserSupport() {
      let isFileSystemAccessApiSupported = false;

      try {
        // Check if showDirectoryPicker is available
        isFileSystemAccessApiSupported =
          'showDirectoryPicker' in window && typeof window.showDirectoryPicker === 'function';

        // Check if navigator.storage.getDirectory is available
        if (isFileSystemAccessApiSupported) {
          try {
            // Check if getDirectoryHandle is available
            isFileSystemAccessApiSupported =
              isFileSystemAccessApiSupported &&
              'getDirectoryHandle' in
                Object.getPrototypeOf(await window.navigator.storage.getDirectory());
          } catch (error) {
            // If there is an error when calling storage API, consider it unsupported
            isFileSystemAccessApiSupported = false;
          }
        }
      } catch (error) {
        // If there is any error, consider it unsupported
        isFileSystemAccessApiSupported = false;
      }

      // Check if the browser is Chromium-based
      const isChromiumBased =
        /Chrome|Edge|Edg|OPR/.test(navigator.userAgent) &&
        /Google Inc|Microsoft|Opera/.test(navigator.vendor);

      return {
        isFileSystemAccessApiSupported,
        isChromiumBased,
        isSupported: isFileSystemAccessApiSupported && isChromiumBased,
      };
    }

    $scope.doDownload = async function (
      item,
      projectId,
      email,
      isUnzipFile = false,
      dirHandle = null
    ) {
      var data = {
        email: email,
        os: '',
      };
      console.log('doDownload', item);

      // Kiểm tra nếu tệp có đuôi là .zip
      var isZipFile = item.name && item.name.toLowerCase().endsWith('.zip');

      console.log('isZipFile', isZipFile);

      var myJSON = JSON.stringify(data);
      var encodedString = window.btoa(myJSON.toString());

      // var type = (asZip) ? 3 : 1;
      var type = 1;
      var url = configServer.API_URL + '/download/files/' + item.id;
      url +=
        '?project_id=' +
        projectId +
        '&folder_id=' +
        item.parent_folder_id +
        '&download_type=' +
        type +
        '&auth_token=' +
        session.getAccessToken() +
        '&data=' +
        encodedString;

      // Check if the file is a ZIP file and if we want to unzip it
      if (isZipFile && isUnzipFile) {
        // Check browser support for File System Access API
        const browserSupport = await checkBrowserSupport();

        if (browserSupport.isSupported) {
          $scope.openPopupWaiting('MY_EMAIL.UNZIP_PROGRESS');
          try {
            if (dirHandle) {
              await extractZipFileWithDirectory(url, dirHandle);
            } else {
              try {
                const selectedDirHandle = await getTargetDirectory();
                await extractZipFileWithDirectory(url, selectedDirHandle);
              } catch (dirError) {
                console.error('Failed to select directory:', dirError);
              }
            }
          } catch (error) {
            console.error('Error extracting ZIP file:', error);
            Util.createToast({
              className: 'error',
              content: Util.translate('MY_EMAIL.UNZIP_ERROR'),
            });
          }
        }
      } else {
        if (isZipFile) {
          $scope.openPopupWaiting('MY_EMAIL.DECRYPT_ZIP_PROGRESS');
          downloadZipFile(url)
            .then(function (blob) {
              var downloadUrl = window.URL.createObjectURL(blob);
              var a = document.createElement('a');
              a.href = downloadUrl;
              var downloadName = item.name;
              if (downloadName && downloadName.toLowerCase().endsWith('.enc')) {
                downloadName = downloadName.substring(0, downloadName.length - 4);
              }
              a.download = downloadName || 'download.zip';
              document.body.appendChild(a);
              a.click();
              a.remove();
              window.URL.revokeObjectURL(downloadUrl);

              $rootScope.$broadcast('close_popup');
            })
            .catch(function (error) {
              console.error('Download failed:', error);
              $rootScope.$broadcast('close_popup');
              Util.createToast({
                className: 'danger',
                content: 'DOWNLOAD_ERR',
              });
            });
        } else {
          $.fileDownload(url, { httpMethod: 'GET' });
        }
      }
    };

    $scope.openFolder = function (item, projectId) {
      if (item.status !== 1) {
        return;
      }

      if (item.folder === false) {
        $scope.showViewOnline(item, $scope.currentUser.mail_address);
      } else {
        $state.go('myEmail', { folder_id: item.id });
      }
    };

    $scope.showViewOnline = function (item, email) {
      var newTab;
      if (item.is_encrypt !== 0 && item.is_encrypt !== 3) {
        // newTab = window.open('about:blank', '_blank');
      }
      var data = {
        email: email,
        os: '',
      };
      var myJSON = JSON.stringify(data);
      var encodedString = window.btoa(myJSON.toString());

      var params = {
        file_id: item.id,
        data: encodedString,
      };
      $scope.getFileLicenseInfo = function (file, cb, err) {
        var param = {
          project_id: $scope.projectId,
          folder_id: file.parent_folder_id,
        };
        Util.createRequest(
          configServer.API_URL + '/files/' + file.id + '/drm/license',
          'GET',
          param,
          function (response) {
            var status = response.status;
            if (status === 200) {
              // store user into session
              cb && cb(response.data);
            } else {
              err && err(response.data);
            }
          },
          function (errResponse) {
            Util.createToast({
              className: 'danger',
              content: 'SERVER_ERROR.' + errResponse.status,
            });
            err && err(errResponse);
          }
        );
      };

      $scope.getFileLicenseInfo(
        item,
        function (response) {
          $scope.printable = response.file_project.printable;
          $scope.wmSubSetting = {
            wm_text:
              session.getUser().mail_address +
              ' ' +
              new Date().toLocaleDateString('en-US', {
                month: '2-digit',
                day: '2-digit',
                year: 'numeric',
              }),
            wm_font_size: 50,
            wm_color: 'RGB(0,0,0)',
            wm_position: 'diagonal',
          };
          Util.createRequest(
            configServer.API_URL + '/files/view/link',
            'GET',
            params,
            function (response) {
              var status = response.status;
              if (status === 200) {
                console.log('item', item);

                if (item.is_encrypt === 0 || item.is_encrypt === 3) {
                  showViewOnlineNonProtectModal(response.data.url_file, item.name);
                } else {
                  $scope.viewerUrl =
                    AppConfig.VIEWER_URL +
                    '?id=' +
                    response.data.content_id +
                    '&ak=' +
                    response.data.key_id +
                    '&pr=' +
                    ($scope.printable === 1 ? 1 : 0) +
                    '&wc=' +
                    $scope.wmSubSetting.wm_color +
                    '&ws=' +
                    $scope.wmSubSetting.wm_font_size +
                    '&wp=' +
                    $scope.wmSubSetting.wm_position +
                    '&wt=' +
                    $scope.wmSubSetting.wm_text;
                  showViewOnlineModal($scope.viewerUrl);
                  // if (newTab) {
                  //   newTab.location.href = $scope.viewerUrl;
                  // } else {
                  //   window.open($scope.viewerUrl, '_blank');
                  // }
                }

                function getExtension(path) {
                  var basename = /[^/\\&\?]+\.\w{3,4}(?=([\?#&].*$|$))/g.exec(path);
                  var fileName = basename && basename[0];
                  return fileName && fileName.split('.').pop();
                }

                function showViewOnlineModal(viewerUrl) {
                  return $uibModal
                    .open({
                      templateUrl: 'components/modal-template/view_online_modal.html',
                      size: 'xl',
                      backdrop: 'static',
                      controller: [
                        '$scope',
                        '$rootScope',
                        '$uibModalInstance',
                        function ($scope, $rootScope, $uibModalInstance) {
                          $scope.onClose = function () {
                            $uibModalInstance.close();
                          };
                          $scope.viewerUrl = viewerUrl;

                          $timeout(function () {
                            var iframe = document.querySelector('iframe');
                            if (iframe) {
                              iframe.addEventListener('load', function () {
                                this.focus();
                                console.log('Iframe loaded and focused successfully');
                              });
                            }
                          });
                        },
                      ],
                    })
                    .result.catch(function (resp) {
                      if (['cancel', 'backdrop click', 'escape key press'].indexOf(resp) === -1) {
                        throw resp;
                      }
                    });
                }

                function showViewOnlineNonProtectModal(fileUrl, name) {
                  return $uibModal
                    .open({
                      templateUrl: 'components/modal-template/view-noneprotect-tmpl.html',
                      size: 'xl',
                      backdrop: 'static',
                      controller: [
                        '$scope',
                        '$rootScope',
                        '$uibModalInstance',
                        function ($scope, $rootScope, $uibModalInstance) {
                          $scope.loading = true;
                          // define show type [-1: not support, 1: doc, 2: image, 3: txt,audio/video]
                          $scope.showType = -1; // default not support
                          $scope.isHideToolbar = false;
                          $scope.autoHideToolbarTime = 2000; //milliseconds

                          $timeout(function () {
                            var iframe = document.querySelector('iframe');
                            if (iframe) {
                              iframe.addEventListener('load', function () {
                                this.focus();
                                console.log('Iframe loaded and focused successfully');
                              });
                            }
                          });

                          $scope.onClose = function () {
                            $uibModalInstance.close();
                            // remove event listener
                            if ($scope.viewer) {
                              $scope.viewer.destroy();
                            }
                          };
                          $scope.name = name;

                          var fileExt = getExtension(fileUrl);
                          fileExt && (fileExt = fileExt.toLowerCase());
                          if (ViewerSupportType.SUPPORT_TYPES_DOC.indexOf(fileExt) !== -1) {
                            $scope.showType = 1;
                            var link_file = ViewerUrl.ONE_DRIVE + encodeURIComponent(fileUrl);
                            if (fileExt === 'pdf') {
                              // var path = encodeURIComponent(fileUrl).substring(4);
                              link_file = ViewerUrl.PDF_JS + fileUrl;
                            }

                            $scope.loading = false;
                            $scope.currentUrl = $sce.trustAsResourceUrl(link_file);
                          } else {
                            if (ViewerSupportType.SUPPORT_TYPES_IMG.indexOf(fileExt) !== -1) {
                              $scope.showType = 2;
                            } else if (ViewerSupportType.SUPPORT_AUDIO.indexOf(fileExt) !== -1) {
                              $scope.showType = 3;
                            } else if (ViewerSupportType.SUPPORT_VIDEO.indexOf(fileExt) !== -1) {
                              $scope.showType = 4;
                            } else {
                              $scope.showType = -1;
                              $scope.loading = false;
                            }
                            $scope.currentUrl = $sce.trustAsResourceUrl(fileUrl);
                          }

                          // set time auto hide toolbar
                          $timeout(function () {
                            $scope.isHideToolbar = true;
                          }, $scope.autoHideToolbarTime);

                          var timeoutPromise;
                          $(document).click(function () {
                            $('.toolbar-content').addClass('toolbar-show');
                            if (timeoutPromise) {
                              $timeout.cancel(timeoutPromise);
                            }
                            timeoutPromise = $timeout(function () {
                              $('.toolbar-content').removeClass('toolbar-show');
                            }, $scope.autoHideToolbarTime);
                          });
                        },
                      ],
                    })
                    .result.catch(function (resp) {
                      if (['cancel', 'backdrop click', 'escape key press'].indexOf(resp) === -1)
                        throw resp;
                    });
                }
              } else {
                if (newTab) newTab.close();
                Util.createToast({
                  className: 'danger',
                  content: 'SERVER_ERROR.' + status,
                });
              }
            },
            function (error) {
              if (newTab) newTab.close();
              Util.createToast({
                className: 'danger',
                content: 'SERVER_ERROR.' + error.status,
              });
            }
          );
        },
        function (error) {
          if (newTab) newTab.close();
        }
      );
    };

    $scope.formatDateTime = function (date) {
      return Util.formatDate(moment(date), $scope.currentUser.time_zone, 'MM/DD/YYYY HH:mm:ss');
    };

    $scope.convertFileSize = function (size) {
      return Util.convertFileSize(size);
    };

    // Get group from mime type
    $scope.getGroupFromMimeType = function (file) {
      return Util.getGroupFromMimeType(file);
    };

    $scope.drawFilePath = function () {
      //call project get project name
      Util.createRequest(
        configServer.API_URL + '/projects/' + $scope.projectId,
        'GET',
        {},
        function (response) {
          if (response.status === 200) {
            $scope.projectName = response.data.name;
            getCurrentFolder();
          }
        }
      );
    };

    function getFilePath() {
      if (
        $scope.currentFolder.folder.parent_folder_id === undefined ||
        $scope.currentFolder.folder.parent_folder_id === null ||
        $scope.currentFolder.folder.parent_folder_id === 0
      ) {
        $scope.filePath = Util.translate('COMMON.MY_EMAIL');
      } else {
        $scope.listFolder = [];
        $scope.loadPath = '<span>' + Util.translate('COMMON.LOADING') + '</span>';
        $scope.isLoading = true;
        Util.createRequest(
          configServer.API_URL + '/folders/' + $scope.folderId + '/path',
          'GET',
          { project_id: $scope.projectId },
          function (response) {
            if (response.status === 200) {
              var folders = response.data;
              $scope.separator =
                '&nbsp;<span class="separator-icon small d-inline-block"><i class="fa fa-chevron-right" aria-hidden="true"></i></span>&nbsp;';
              $scope.sentFiles =
                '<a href="#!/my-email/0" >' + Util.translate('COMMON.MY_EMAIL') + '</a>';
              $scope.currentFol = '';
              // apply folder tree link
              if (folders && folders.length > 0) {
                for (var i = 0; i < folders.length; i++) {
                  if (i !== folders.length - 1) {
                    $scope.listFolder.push(folders[i]);
                  } else {
                    $scope.folderBefor =
                      $scope.separator +
                      '<a href="#!/my-email/' +
                      folders[i].folder_id +
                      '">' +
                      folders[i].name +
                      '</a>';
                  }
                }
              }
              $scope.currentFol =
                $scope.separator + '<span>' + $scope.currentFolder.folder.name + '</span>';
              $scope.isLoading = false;
            } else {
              $scope.isLoading = false;
              Util.createToast({ className: 'danger', content: 'SERVER_ERROR.' + response.status });
            }
          },
          function (error) {
            Util.createToast({
              className: 'danger',
              content: 'SERVER_ERROR.' + error.status,
            });
          }
        );
      }
    }

    function getCurrentFolder() {
      Util.createRequest(
        configServer.API_URL + '/folders/' + $scope.folderId,
        'GET',
        { project_id: $scope.projectId },
        function (response) {
          if (response.status === 200) {
            $scope.currentFolder = response.data;
            getFilePath();
          } else {
            Util.createToast({ className: 'danger', content: 'SERVER_ERROR.' + response.status });
          }
        },
        function (error) {
          Util.createToast({
            className: 'danger',
            content: 'SERVER_ERROR.' + error.status,
          });
        }
      );
    }

    $scope.showFileVersion = function (file, projectId) {
      return $uibModal
        .open({
          templateUrl: 'components/modal-template/file_version.html',
          size: 'sm',
          resolve: {
            projectId: function () {
              return projectId;
            },
            file: function () {
              return file;
            },
            extractZipFileWithDirectory: function () {
              return extractZipFileWithDirectory;
            },
            openPopupWaiting: function () {
              return $scope.openPopupWaiting;
            },
          },
          controller: [
            '$scope',
            '$rootScope',
            '$uibModalInstance',
            '$translate',
            '$cookies',
            'configServer',
            'projectId',
            'file',
            'extractZipFileWithDirectory',
            'openPopupWaiting',
            function (
              $scope,
              $rootScope,
              $uibModalInstance,
              $translate,
              $cookies,
              configServer,
              projectId,
              file,
              extractZipFileWithDirectory,
              openPopupWaiting
            ) {
              $scope.loading = false;
              function getListVersion(cb) {
                $scope.loading = true;
                var params = {
                  project_id: projectId,
                  folder_id: $stateParams.folder_id ? $stateParams.folder_id : '0',
                };
                Util.createRequest(
                  configServer.API_URL + '/files/' + file.id + '/versions',
                  'GET',
                  params,
                  function (response) {
                    if (response.status === 200) {
                      $scope.isLoading = false;
                      $scope.fileVersions = response.data;
                      var timezone = session.getUser().time_zone;
                      var lang = session.getUser().lang;

                      angular.forEach($scope.fileVersions, function (fileVersion) {
                        fileVersion.full_name =
                          lang === 'ja'
                            ? fileVersion.last_name + ' ' + fileVersion.first_name
                            : fileVersion.first_name + ' ' + fileVersion.last_name;

                        fileVersion.create_date = Util.formatDate(
                          new Date(fileVersion.create_date),
                          timezone,
                          'MM/DD/YYYY HH:mm:ss',
                          lang
                        );
                      });
                    } else {
                      $scope.isLoading = false;
                      Util.createToast({
                        className: 'danger',
                        content: 'SERVER_ERROR.' + response.status,
                      });
                    }
                  },
                  function (error) {
                    Util.createToast({
                      className: 'danger',
                      content: 'SERVER_ERROR.' + error.status,
                    });
                  }
                );
              }

              getListVersion();

              $scope.makeCurrent = function (version) {
                var params = {
                  project_id: projectId,
                  file_version_id: version.id,
                  folder_id: file.parent_folder_id ? file.parent_folder_id : '0',
                };
                Util.createRequest(
                  configServer.API_URL + '/files/' + file.id + '/versions/reverse',
                  'POST',
                  params,
                  function (response) {
                    if (response.status === 200) {
                      getListVersion();
                      $rootScope.$broadcast('load_list_items', 'loadList');
                    } else {
                      $scope.isLoading = false;
                      Util.createToast({
                        className: 'danger',
                        content: 'SERVER_ERROR.' + response.status,
                      });
                    }
                  },
                  function (error) {
                    Util.createToast({
                      className: 'danger',
                      content: 'SERVER_ERROR.' + error.status,
                    });
                  }
                );
              };

              $scope.removeVersion = function (version) {
                var params = {
                  project_id: projectId,
                  file_version_id: version.id,
                  folder_id: file.parent_folder_id ? file.parent_folder_id : '0',
                };

                Util.createRequest(
                  configServer.API_URL + '/files/' + file.id + '/versions',
                  'DELETE',
                  params,
                  function (response) {
                    if (response.status === 200) {
                      getListVersion();
                      $rootScope.$broadcast('load_list_items', 'loadList');
                    } else {
                      $scope.isLoading = false;
                      Util.createToast({
                        className: 'danger',
                        content: 'SERVER_ERROR.' + response.status,
                      });
                    }
                  },
                  function (error) {
                    Util.createToast({
                      className: 'danger',
                      content: 'SERVER_ERROR.' + error.status,
                    });
                  }
                );
              };

              $scope.doDownloadFileVersion = function (version) {
                var isZipFile = version.title && version.title.toLowerCase().endsWith('zip');

                if (isZipFile) {
                  $scope.showDownloadOptionsModal(version);
                  return;
                }

                var data = {
                  email: session.getUser().mail_address,
                  os: '',
                };
                var myJSON = JSON.stringify(data);
                var encodedString = window.btoa(myJSON.toString());
                var type = 1;
                var url = configServer.API_URL + '/download/files/' + file.id;
                url +=
                  '?project_id=' +
                  projectId +
                  '&folder_id=' +
                  file.parent_folder_id +
                  '&download_type=' +
                  type +
                  '&auth_token=' +
                  session.getAccessToken() +
                  '&data=' +
                  encodedString +
                  '&file_version=' +
                  version.id;

                $.fileDownload(url, { httpMethod: 'GET' })
                  .done(function () {
                    console.log('Download succeeded');
                  })
                  .fail(function () {
                    console.error('Download failed');
                  });
              };

              $scope.showDownloadOptionsModal = function (version) {
                return $uibModal
                  .open({
                    templateUrl:
                      'components/modal-template/confirm_download_or_unzip_and_save_folder.html',
                    size: 'md',
                    resolve: {
                      version: function () {
                        return version;
                      },
                      projectId: function () {
                        return projectId;
                      },
                      file: function () {
                        return file;
                      },
                      openPopupWaiting: function () {
                        return openPopupWaiting;
                      },
                    },
                    controller: [
                      '$scope',
                      '$uibModalInstance',
                      '$translate',
                      'version',
                      'projectId',
                      'file',
                      'openPopupWaiting',
                      '$rootScope',
                      function (
                        $scope,
                        $uibModalInstance,
                        $translate,
                        version,
                        projectId,
                        file,
                        openPopupWaiting,
                        $rootScope
                      ) {
                        $translate([
                          'VIEW_DOWNLOAD.CONFIRM_DOWNLOAD_OR_UNZIP_AND_SAVE_FOLDER_TITLE',
                          'VIEW_DOWNLOAD.CONFIRM_DOWNLOAD_OR_UNZIP_AND_SAVE_FOLDER_MSG',
                          'VIEW_DOWNLOAD.JUST_DOWNLOAD_BUTTON',
                          'VIEW_DOWNLOAD.DOWNLOAD_AND_UNZIP_SAVE_BUTTON',
                        ]).then(function (translations) {
                          $scope.opts = {
                            title:
                              translations[
                                'VIEW_DOWNLOAD.CONFIRM_DOWNLOAD_OR_UNZIP_AND_SAVE_FOLDER_TITLE'
                              ],
                            message:
                              translations[
                                'VIEW_DOWNLOAD.CONFIRM_DOWNLOAD_OR_UNZIP_AND_SAVE_FOLDER_MSG'
                              ],
                            justDownloadLabel: translations['VIEW_DOWNLOAD.JUST_DOWNLOAD_BUTTON'],
                            downloadAndUnzipLabel:
                              translations['VIEW_DOWNLOAD.DOWNLOAD_AND_UNZIP_SAVE_BUTTON'],
                          };
                        });

                        // Create URL download
                        function createDownloadUrl() {
                          var data = {
                            email: session.getUser().mail_address,
                            os: '',
                          };
                          var myJSON = JSON.stringify(data);
                          var encodedString = window.btoa(myJSON.toString());
                          var type = 1;
                          var url = configServer.API_URL + '/download/files/' + file.id;
                          url +=
                            '?project_id=' +
                            projectId +
                            '&folder_id=' +
                            file.parent_folder_id +
                            '&download_type=' +
                            type +
                            '&auth_token=' +
                            session.getAccessToken() +
                            '&data=' +
                            encodedString +
                            '&file_version=' +
                            version.id;
                          return url;
                        }

                        $scope.onClose = function () {
                          $uibModalInstance.close();
                        };

                        // Only download the ZIP file
                        $scope.onJustDownload = function () {
                          var url = createDownloadUrl();
                          openPopupWaiting('MY_EMAIL.DECRYPT_ZIP_PROGRESS');
                          downloadZipFile(url)
                            .then(function (blob) {
                              var downloadUrl = window.URL.createObjectURL(blob);
                              var a = document.createElement('a');
                              a.href = downloadUrl;
                              var downloadName = file.name;
                              if (downloadName && downloadName.toLowerCase().endsWith('.enc')) {
                                downloadName = downloadName.substring(0, downloadName.length - 4);
                              }
                              a.download = downloadName || 'download.zip';
                              document.body.appendChild(a);
                              a.click();
                              a.remove();
                              window.URL.revokeObjectURL(downloadUrl);

                              $rootScope.$broadcast('close_popup');
                            })
                            .catch(function (error) {
                              console.error('Download failed:', error);
                              $rootScope.$broadcast('close_popup');
                              Util.createToast({
                                className: 'danger',
                                content: 'DOWNLOAD_ERR',
                              });
                            });
                          $uibModalInstance.close();
                        };

                        // Download and unzip file ZIP
                        $scope.onUnzipAndSaveFolder = function () {
                          var url = createDownloadUrl();
                          getTargetDirectory()
                            .then(function (dirHandle) {
                              openPopupWaiting('MY_EMAIL.UNZIP_PROGRESS');
                              extractZipFileWithDirectory(url, dirHandle)
                                .then(function () {
                                  console.log('Unzip completed');
                                })
                                .catch(function (error) {
                                  console.error('Unzip failed:', error);
                                  Util.createToast({
                                    className: 'error',
                                    content: Util.translate('MY_EMAIL.UNZIP_ERROR'),
                                  });
                                });
                            })
                            .catch(function (error) {
                              console.error('Failed to select directory:', error);
                              Util.createToast({
                                className: 'warning',
                                content: Util.translate('MY_EMAIL.SELECT_DIRECTORY_ERROR'),
                              });
                            });
                          $uibModalInstance.close();
                        };
                      },
                    ],
                  })
                  .result.catch(function (resp) {
                    if (['cancel', 'backdrop click', 'escape key press'].indexOf(resp) === -1) {
                      throw resp;
                    }
                  });
              };

              $scope.onClose = function () {
                $uibModalInstance.close();
              };
            },
          ],
        })
        .result.catch(function (resp) {
          if (['cancel', 'backdrop click', 'escape key press'].indexOf(resp) === -1) {
            throw resp;
          }
        });
    };

    $scope.openPopupWaiting = function (messageKey) {
      return $uibModal
        .open({
          templateUrl: 'components/modal-template/please-wait-modal.html',
          size: 'md',
          backdrop: 'static',
          keyboard: false,
          controller: [
            '$scope',
            '$uibModalInstance',
            'Util',
            function ($scope, $uibModalInstance, Util) {
              $scope.opts = {
                message: Util.translate(messageKey),
              };

              // Close modal when receiving the `close_popup` event
              $scope.$on('close_popup', function () {
                $uibModalInstance.close();
              });
            },
          ],
        })
        .result.catch(function (resp) {
          if (['cancel', 'backdrop click', 'escape key press'].indexOf(resp) === -1) {
            throw resp;
          }
        });
    };
  },
]);
