<?php

namespace Hura8\System;

final class CronProcess
{
    private $pid;

    /* @var FileSystem $objFileSystem */
    private $objFileSystem;

    const LOG_DIR = VAR_DIR . '/log/';
    private $max_allow_run_time = 1800; // in seconds - max cron run time.

    public function __construct($pid, $max_allow_run_time = 1800) {
        $this->pid = $pid;
        $this->objFileSystem = new FileSystem(self::LOG_DIR);
        $this->max_allow_run_time = $max_allow_run_time;
    }

    public function getPidFile() {
        return $this->objFileSystem->getFile($this->pid);
    }

    /**
     * Check if the process is running. True if:
     * - has pid file
     * - the file's create-time within the time() and time() - $this->max_allow_run_time
     *
     * Else: False and remove pid file if exist
     * @return bool
     */
    public function isRunning() : bool {

        $file_exist = ($this->objFileSystem->getFile($this->pid));
        if(!$file_exist) {
            return false;
        }

        $last_modified_time = $this->objFileSystem->getFileLastModifiedTime($this->pid);

        if($last_modified_time > 0 && $last_modified_time < time() - $this->max_allow_run_time) {

            echo "Pid File exists but too old. Trying to auto-delete now". PHP_EOL;

            if($this->objFileSystem->delete($this->pid)){
                echo "File is deleted successfully". PHP_EOL;
            }else{
                echo "Auto-delete fails. File needs to be removed manually. Path: ". $this->objFileSystem->getFilename($this->pid). PHP_EOL;
            }

            return false;
        }

        return true;
    }

    public function start() {
        return $this->objFileSystem->writeFile($this->pid, time());
    }

    public function finish() {
        return $this->objFileSystem->delete($this->pid);
    }

}
