<?php

namespace auctionforge\inc\controllers;

use WP_Filesystem_Base;

class HummingbirdSupport
{
    public $terms = array();

    public function run()
    {
        if (self::isHummingbirdActive()) {
            add_filter('wphb_page_cache_custom_terms', array($this, 'page_cache_auction_terms'), 10, 1);
        }
    }

    public function page_cache_auction_terms($terms) {
        $terms[] = BidspiritLots::TAX_AUCTION_TYPE;
        return $terms;
    }

    /**
     * @return bool
     */
    public static function isHummingbirdActive()
    {
        if (is_plugin_active('wp-hummingbird/wp-hummingbird.php')) {
            return true;
        }
        return false;
    }

    public static function clearCache($id)
    {
        if (self::isHummingbirdActive()) {
            do_action('wphb_clear_page_cache', $id);
        }
    }

    public static function clearAllCache()
    {
        if (self::isHummingbirdActive()) {
            do_action('wphb_clear_page_cache');
        }
    }

    public static function clearCacheByUrl($url)
    {
        if (self::isHummingbirdActive()) {
            return self::clearCacheByUri(self::prepareUri($url));
        }
    }

    public static function clearCacheOnHomePage()
    {
        if (self::isHummingbirdActive()) {
            global $wp_filesystem;

            $uri = self::prepareUri(get_option('siteurl'));
            $path = self::buildPath($uri);
            $mobilePath = self::buildPath($uri, true);

            if (is_null($wp_filesystem)) {
                return true;
            }

            $paths = [
                $path => $wp_filesystem->dirlist($path),
                $mobilePath => $wp_filesystem->dirlist($mobilePath),
            ];

            foreach ($paths as $currentPath => $fileList) {
                if (!empty($fileList)) {
                    foreach ($fileList as $asset) {
                        if ($asset["type"] == "f" && $asset["name"] != "index.html") {
                            $wp_filesystem->delete($currentPath . $asset['name'], true, $asset['type']);
                        }
                    }
                }

                if (empty($wp_filesystem->dirlist($currentPath))) {
                    $wp_filesystem->delete($currentPath);
                }
            }

            if (PolylangSupport::isPolylangActive()) {
                $homeUrl = pll_home_url(MultiLanguageSupport::getSecondLangCode());
                self::clearCacheByUrl($homeUrl);
            }
        }
    }


    public static function clearCacheByUri($uri)
    {
        if (self::isHummingbirdActive()) {
            /**
             * @type WP_Filesystem_Base $wp_filesystem
             */
            global $wp_filesystem;
            $path = self::buildPath($uri);
            $mobilePath = self::buildPath($uri, true);

            if (is_null($wp_filesystem)) {
                return true;
            }

            $paths = [
                $path => $wp_filesystem->dirlist($path),
                $mobilePath => $wp_filesystem->dirlist($mobilePath),
            ];

            foreach ($paths as $currentPath => $fileList) {
                if (!empty($fileList)) {
                    foreach ($fileList as $asset) {
                        if (!$wp_filesystem->delete($currentPath . $asset['name'], true, $asset['type'])) {
                            return false;
                        }
                    }
                }

                if (empty($wp_filesystem->dirlist($currentPath)) && !$wp_filesystem->delete($currentPath)) {
                    return false;
                }
            }
        }
    }

    public static function prepareUri($url)
    {
        if (is_string($url) || is_array($url)) {
            return preg_replace("/(https?:\/\/)/", "", $url);
        } else {
            return "false";
        }
    }

    private static function buildPath($uri, $includeMobile = false)
    {
        if ($includeMobile) {
            $path = ABSPATH . "wp-content/wphb-cache/cache/mobile/" . $uri . "/";
        } else {
            $path = ABSPATH . "wp-content/wphb-cache/cache/" . $uri . "/";
        }
        return preg_replace("/\/\//", "/", $path);
    }

    /**
     * @return mixed
     */
    public function getTerms()
    {
        return $this->terms;
    }

    /**
     * @param  mixed  $term
     */
    public function setTerms($term)
    {
        $this->terms[] = $term;
    }

    private static $_instance = null;

    private function __construct() {}

    protected function __clone() {}

    static public function getInstance() {
        if(is_null(self::$_instance))
        {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
}
