<?php

/**
 * Created by PhpStorm.
 * User: Joe
 * Date: 9/7/16
 * Time: 9:52 AM
 */
namespace DVCNotifier;

class Log {
	private $file;
	private $settings = array(
		'uri' => '',
	);

	public function __construct( $settings ) {
		$this->settings = array_merge( $this->settings, $settings );
		$this->file     = fopen( $this->settings['uri'] . 'results-' . time() . '.txt', 'w' );
	}

	public function purge() {
		if ( is_dir( $this->settings['uri'] ) ) {
			$logs = scandir( $this->settings['uri'] );
			foreach ( $logs as $key => $log ) {
				if ( strpos( $log, 'results-' ) !== 0 ) {
					unset( $logs[ $key ] );
				}
			}

			if ( count( $logs ) > $this->settings['keep'] ) {
				rsort( $logs );
				foreach ( $logs as $key => $log ) {
					if ( $key >= $this->settings['keep'] ) {
						unlink( $this->settings['uri'] . $log );
						unset( $logs[ $key ] );
					}
				}
			}
		}
	}

	/**
	 * @param $message
	 */
	public function write( $message ) {
		if ( is_array( $message ) ) {
			$message = wp_json_encode( $message );
		}
		fwrite( $this->file, date( 'Y-m-d H:i:s', time() ) . ' - ' . $message . "\n" );
	}

	public function close() {
		$this->write( 'Application shut down.' );
		fclose( $this->file );
	}
}
