<?php
/*
    StaticSite

    The resulting output of crawling the WordPress site

    Site URLs are all made absolute for easier rewriting during deployment
*/

namespace StaticDeploy;

use RecursiveIteratorIterator;
use RecursiveDirectoryIterator;

class StaticSite {

    private static string $crawled_site_path;

    /**
     * Add PathInfo contents to static site
     */
    public static function add(
        PathInfo $path_info,
    ): void {
        FilesHelper::writePathInfo(
            self::getPath(),
            $path_info,
        );
    }

    public static function getPath(): string {
        if ( ! isset( self::$crawled_site_path ) ) {
            self::$crawled_site_path = Options::getValue( 'crawledSitePath' );
        }
        return SiteInfo::getPath( 'uploads' ) . self::$crawled_site_path;
    }

    /**
     * Delete StaticSite files
     */
    public static function delete(): void {
        WsLog::l( 'Deleting StaticSite files' );

        if ( is_dir( self::getPath() ) ) {
            FilesHelper::deleteDirWithFiles( self::getPath() );

            // The crawled file data is not useful without
            // StaticSite files.
            CrawledFiles::truncate();
        }
    }

    /**
     *  Get all paths in StaticSite
     *
     *  @return string[] StaticSite paths
     */
    public static function getPaths(): array {
        $static_site_dir = self::getPath();

        if ( ! is_dir( $static_site_dir ) ) {
            return [];
        }

        $paths = [];

        $iterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator(
                $static_site_dir,
                RecursiveDirectoryIterator::SKIP_DOTS
            )
        );

        foreach ( $iterator as $filename => $file_object ) {
            $base_name = basename( (string) $filename );
            if ( $base_name !== '.' && $base_name !== '..' ) {
                $real_filepath = realpath( $filename );

                if ( is_string( $real_filepath ) ) {
                    $paths[] = str_replace( $static_site_dir, '', $real_filepath );
                }
            }
        }

        sort( $paths );

        return $paths;
    }
}
