<?php
// This file is part of the Studyplan plugin for Moodle
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <https://www.gnu.org/licenses/>.
/**
 * Generate random grades and feedback to initialize development environment
 * @package    local_treestudyplan
 * @copyright  2023 P.M. Kuipers - Chris Zuber
 * @license    https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

namespace local_treestudyplan\local;

use Exception;
/**
 * Generate random grades and feedback to initialize development environment
 */
class randomimage {

    /**
     * Image width
     * @var int
     */
    private $width;

    /**
     * Image height
     * @var int
     */
    private $height;

    /**
     * Number of shapes to draw
     * @var int
     */
    private $shapes;

    /**
     * Image name
     * @var string
     */
    public $name;

    /**
     * Image temporary file
     * @var string
     */
    public $tempfile;

    /**
     * Various available styles for arcs
     * @var array
     */
    const ARC_STYLES = [
        IMG_ARC_PIE,
        IMG_ARC_CHORD,
        IMG_ARC_EDGED,
        IMG_ARC_NOFILL,
    ];

    /**
     * Create a random polygon with number of points between 0 & $maxpts
     * @param  \GdImage  $im      The image reource
     * @param  int  $maxpts Max number of point to use
     * @return void
     */
    private function random_polygon($im, int $maxpts = 20) {
        $color = imagecolorallocatealpha($im, ...$this->random_color_alpha());
        $numpoints = \random_int(3, $maxpts);
        $pts = $this->random_pts($numpoints);
        imagefilledpolygon($im, $pts, $color);
    }

    /**
     * Creates a random arc of a random color
     * @param \GdImage $im The image resource
     * @return void
     */
    private function random_arc($im) {
        $cx = \random_int(0, $this->width);
        $cy = \random_int(0, $this->height);
        $w = \random_int(0, $this->width);
        $h = \random_int(0, $this->height);
        $s = \random_int(0, 360);
        $e = \random_int(0, 360);
        $col = imagecolorallocatealpha($im, ...$this->random_color_alpha());
        $style = self::ARC_STYLES[\random_int(0, 3)];
        imagefilledarc($im, $cx, $cy, $w, $h, $s, $e, $col, $style);
    }

    /**
     * Generates an array of random alpha color values.
     * @return Array [r, g, b, a]
     */
    private function random_color_alpha(): Array {
        return [
            \random_int(0, 255),
            \random_int(0, 255),
            \random_int(0, 255),
            \random_int(0, 127),
        ];
    }

    /**
     * Generates a set of random points for a polygon [x1, y1, x2, y2, ...]
     * @param  integer $length Number of sets of points to generate
     * @return Array           The resulting array of points
     */
    private function random_pts($length): Array {
        $pts = [];
        for ($n = 0; $n < $length; $n++) {
            $pts[] = \random_int(0, $this->width);
            $pts[] = \random_int(0, $this->height);
        }
        return $pts;
    }

    /**
     * Create new random image
     * @param int $shapes Number of shapes
     * @param int $width Width of the images generated
     * @param int $height Height of the images generated
     */
    public function __construct($shapes=3, $width=256, $height=256) {
        $this->shapes = $shapes;
        $this->width = $width;
        $this->height = $height;

        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $string = '';

        for ($i = 0; $i < 20; $i++) {
            $string .= $characters[\mt_rand(0, strlen($characters) - 1)];
        }

        $this->name = $string.".png";

        $im = imagecreatetruecolor($this->width, $this->height);
        for ($i = 0; $i < $this->shapes; $i++) {
            switch(\random_int(1, 2)) {
                case 1:
                    $this->random_arc($im);
                    break;
                case 2:
                    $this->random_polygon($im);
                    break;
            }
        }
        $this->tempfile = \tempnam("/tmp", "tsp");
        imagepng($im, $this->tempfile);
        imagedestroy($im);
    }

    /**
     * Get image content as string
     * @return string
     */
    public function content() {
        return $this->content = \file_get_contents($this->tempfile);
    }

    /**
     * Destructor for random image object
     */
    public function __destruct() {
        if (isset($this->tempfile) && file_exists($this->tempfile)) {
            unlink($this->tempfile);
        }
    }
}
