<?php

namespace core_next;
class Optimize
{
    static function init()
    {
        global $core_next_set;
        add_filter('show_admin_bar', '__return_false');
        add_filter('intermediate_image_sizes_advanced', [static::class, 'disableImageSizes']);
        remove_filter('the_content', 'wptexturize');
        remove_filter('the_excerpt', 'wptexturize');
        remove_filter('comment_text', 'wptexturize');
        add_filter( 'big_image_size_threshold', '__return_false' );

        if ($core_next_set['avatar_cdn']!=='no') {
            add_filter('get_avatar_url', array(static::class, 'replaceAvatar'), 9999, 3);
        }
    }

    static function replaceAvatar($avatarUrl, $id_or_email, $arrs)
    {
        global $core_next_set;

        $gravatar = $core_next_set['avatar_cdn'];
        if ($gravatar == 'v2ex') {
            $cdnurl = 'cdn.v2ex.com/gravatar';
            $avatarUrl = self::_replaceGravatar($cdnurl, $avatarUrl);
        } elseif ($gravatar == 'geek') {
            $cdnurl = 'sdn.geekzu.org/avatar';
            $avatarUrl = self::_replaceGravatar($cdnurl, $avatarUrl);
        } elseif ($gravatar == 'cn') {
            $cdnurl = 'cn.gravatar.com/avatar';
            $avatarUrl = self::_replaceGravatar($cdnurl, $avatarUrl);
        } elseif ($gravatar == 'qiniu') {
            $cdnurl = 'dn-qiniu-avatar.qbox.me/avatar';
            $avatarUrl = self::_replaceGravatar($cdnurl, $avatarUrl);
        } elseif ($gravatar == 'loli') {
            $cdnurl = 'gravatar.loli.net/avatar';
            $avatarUrl = self::_replaceGravatar($cdnurl, $avatarUrl);
        } elseif ($gravatar == 'gravatar.cn') {
            $cdnurl = 'cravatar.cn/avatar';
            $avatarUrl = self::_replaceGravatar($cdnurl, $avatarUrl);
        } elseif ($gravatar == 'izt6') {
            $cdnurl = 'g.izt6.com/avatar';
            $avatarUrl = self::_replaceGravatar($cdnurl, $avatarUrl);
        }
        return $avatarUrl;
    }

    static function _replaceGravatar($url, $avatarUrl)
    {
        $avatarUrl = str_replace(array(
            "secure.gravatar.com/avatar",
            "www.gravatar.com/avatar",
            "0.gravatar.com/avatar",
            "1.gravatar.com/avatar",
            "2.gravatar.com/avatar",
            "cn.gravatar.com/avatar"
        ), $url, $avatarUrl);
        return $avatarUrl;
    }

    static function disableImageSizes($sizes)
    {
        return [];
    }
}