;
(function() {
    'use strict';

    const
        path = require('path'),
        EventEmitter = require('myevents'),
        apiService = require('app-service');

    angular.module('app.controllers')
        .controller('m_renameCtr', m_renameCtr);
        m_renameCtr.$inject = ['$scope', '$mdDialog', 'item','$timeout']; 
    return;

    function m_renameCtr($scope, $mdDialog, item, $timeout) {
        var vm = $scope;
        let new_item = angular.copy(item);
        vm.closeNew = $mdDialog.cancel;
        let file_info = path.parse(item.name);

        vm.fileName = file_info.name;
        vm.close = $mdDialog.hide;
        vm.error = false;
        let time_promise;

        vm.$watch('fileName', function() {
            $timeout.cancel(time_promise);
            time_promise = $timeout(() => {
                new_item.name = vm.fileName + file_info.ext;
                apiService.check_rename(new_item).then(d => {
                    $scope.$apply(function() {
                        vm.error = d.data;
                    });
                });
            }, 500)
        });

        vm.rename = function() {
 
            if (vm.error) {
                layer.msg('文件名已经存在，请重新设置！');
                return;
            }
            let new_name = vm.fileName + file_info.ext;

            if(/[\\//:*?\"<>|]/.test(new_name)){
                layer.msg('文件名不能包含\\//:*?\"<>|！');
                return;
            }

            new_item.name = new_name;
            apiService.check_rename(new_item).then(d => {
                return d.data;
            }).then((isexit) => {
               
                if (isexit) {
                    layer.msg('文件名已经存在，请重新设置！');
                    return;
                }
                apiService.rename(new_name, item._id).then(d => {
                    $mdDialog.hide();
                    EventEmitter.emit('fileListRefresh');
                });
            });

        }
    }
})();
