'use strict';
require('../modules');
require('../../setting/services/huaweiPermissionSetService');

var module = angular.module('notice.directives');

module.directive('sinoDeviceHuaweiNotice', function($q, CacheService, huaweiPermissionSetService){
    var HUAWEI_PERMISSION_NOTICE = 'huawei_permission_notice';
    return {
        restrict: 'E',
        scope: true,
        templateUrl: 'views/notice/sinoDeviceHuaweiNotice.tpl.html',
        link: function(scope) {
            scope.title = '由于华为手机有它独特的权限设置，为了接收离线提醒和正常使用VPN，请设置权限！';
            scope.$watch(function() {
                return window.device.manufacturer;
            }, function(manufacturer) {
                getAppPermission().then(function(result) {
                    var hasNoticed = CacheService.get(HUAWEI_PERMISSION_NOTICE, false);
                    var show = !hasNoticed || !result;
                    if (manufacturer === 'HUAWEI' && show) {
                        scope.isHuawei = true;
                        CacheService.put(HUAWEI_PERMISSION_NOTICE, true);
                    }
                });
            });

            function getAppPermission() {
                var deferred = $q.defer();
                if(window.SinoNetwork && window.SinoNetwork.getAppPermission) {
                    window.SinoNetwork.getAppPermission(function (result) {
                        deferred.resolve(result);
                    }, function(error) {
                        deferred.reject(new Error('获取华为手机权限失败'));
                    });
                } else {
                    deferred.resolve(false);
                }
                return deferred.promise;
            }

            scope.goToHuaweiPermissionSet = function () {
                huaweiPermissionSetService.goToHuaweiPermissionSet();
            };

            scope.close = function () {
                scope.isHuawei = !scope.isHuawei;
            };

            // 打开系统设置
            scope.setAppPermission = function () {
              if (window.SinoNetwork && window.SinoNetwork.setAppPermission) {
                window.SinoNetwork.setAppPermission();
              }
            };

        }
    };
});
