$Notice={}

$Notice.titleInit=document.title;
$Notice.isShine=false;

$Notice.title=function()
{
    setInterval
    (
        function() 
        {
            var title = document.title;
            if ($Notice.isShine) 
            {
                if (title != '['+$Notice.isShine+']') 
                {
                    document.title = '['+$Notice.isShine+']';    
                } 
                else 
                {
                    document.title = $Notice.titleInit;
                }
            } 
            else 
            {
                document.title = $Notice.titleInit;
            }
        }, 500
    );
}


$Notice.permission=function()
{
    var permission = Notification.permission;
    if(permission === 'granted')
    {
        $M.info('已经授权通知，可以进行你的通知啦！');
    }
    else
    {
        $M.info('用户还未授权，请先授权！');
    }
    return permission;
}

$Notice.init=function(tag,fun)
{
    var permission=$Notice.permission()
    if(tag && permission=='denied')return;
    if(permission !== 'granted')
    {
        try 
        {
            Notification.requestPermission().then
            (
                function (permission) 
                {
                    fun && fun(permission === 'granted' ? true : false)
                    $M.info('用户是否允许通知： ',permission === 'granted' ? '允许' : '拒绝');
                }
            );
        } 
        catch (error) 
        {
            Notification.requestPermission
            (
                function (permission) 
                {
                    $M.info('用户是否允许通知： ',permission === 'granted' ? '允许' : '拒绝');
                }
            ); 
        }
    }
}


$Notice.send=function(obj)
{
    if(!obj)return;
    $Notice.isShine='你有信息';
    $Notice.title();
    var permission=$Notice.permission()
    if(permission === 'granted')
    {
        var notification = new Notification
        (
            obj.title,obj
        );
        var tag;
        
        notification.onclick = function() 
        {
            tag=true;
            $M.info('用户点击了提示');
            if(obj.fun)
            {
                obj.fun(true,obj.data)
            }
            $Notice.isShine=false;
            notification.close();    
        };

        notification.onerror = function() 
        {
            tag=true;
            $M.info('用户提示出错');
            if(obj.fun)
            {
                obj.fun(false,obj.data)
            }
            $Notice.isShine=false;
            notification.close();    
        };

        notification.onclose=function()
        {
            if(tag) return;
            $M.info('用户提示关闭');
            if(obj.fun)
            {
                obj.fun(false,obj.data)
            }
            $Notice.isShine=false;
        }
        return notification
    }
}

$Notice.close=function(notification)
{
    $Notice.isShine=false;
    if(notification)
    {
        notification.close();
    }    
}