<?php

namespace Wizard\MagicForger\Helpers;

/*
 * FileModifier
 *
 * A class that handles all file modifications
 *
 * General flow:
 * Provide a file, a point to insert, and a value to insert.
 * Insert the data.
 *
 * Replacements will consume the insert point.
 * Inserts will maintain the insert point.
 *
 * */
class FileModifier
{
    private $contents;

    public $file_path;

    public function __construct($file_path)
    {
        $this->get_file_contents($file_path);
        $this->file_path = $file_path;
    }

    public function get_file_contents($file_path): void
    {
        // TODO: there needs to be more/any error checking
        $f = fopen($file_path, 'r');
        $this->contents = fread($f, filesize($file_path));
        fclose($f);
    }

    public function write_to_path($file_path = null): void
    {
        $file_path = $file_path ?? $this->file_path;

        $f = fopen($file_path, 'w');
        fwrite($f, $this->contents);
        fclose($f);
    }

    /**
     * Replaces the replacement point with the value in the current contents.
     */
    public function replace($value, $replacement_point): void
    {
        $this->contents = str_replace($replacement_point, $value, $this->contents);
    }

    /**
     * Inserts the value above the insert point in the current contents.
     */
    public function insert($value, $insert_point): void
    {
        // seperate on new lines into an array
        $file_arr = explode("\n", $this->contents);
        $temp_arr = [];

        foreach ($file_arr as $line) {
            if (str_contains($line, $insert_point)) {
                $temp_arr[] = $value;
            }
            $temp_arr[] = $line;
        }

        $this->contents = implode("\n", $temp_arr);
    }
}
