<?php namespace Eae\Support;

// Proccess Manager
Use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;

use GuzzleHttp\Client;
use Log;

class WaveGenerator
{
    private $audioFile = NULL;
    private $saveFolder = NULL;
    private $outputExtenstion = 'json';
    private $waveGeneratorPath = '';

    public function __construct($audioFile)
    {
        $this->waveGeneratorPath = base_path('/utils/wavegenerator.sh');
        $this->saveFolder = public_path() . '/uploads/peaks';
        $this->audioFile = $audioFile;
    }

    public function start()
    {
        $fileExists = $this->_checkFileExistance();

        // Skip if Peak file already exists
        if ($fileExists) {
            return;
        }

        $file = $this->_getFile();
        if (!$file) {
            Log::error("=== ERROR === Peak file failed to generate");

            return;
        }

        $this->_generatePeaks($file);

        // Remove audio file
        unlink($file);
    }

    public function getPeaksData()
    {
        $extension = $this->_getFileExtension();
        $filename = $this->_getFilename();

        if (!$this->_checkFileExistance()) {
            return [0.5, -0.5, 0.3, 0.1, 0.3];
        }

        $path = $this->saveFolder . '/' . $filename . '.' . $extension . '.' . $this->outputExtenstion;
        $file = file_get_contents($path);
        $file = json_decode($file);

        return $file->data;
    }

    private function _checkFileExistance()
    {
        $extension = $this->_getFileExtension();
        $filename = $this->_getFilename();
        $path = $this->saveFolder . '/' . $filename . '.' . $extension . '.' . $this->outputExtenstion;

        return file_exists($path);
    }

    private function _getFile()
    {
        // Create a new guzzle client
        $client = new Client();

        // Extension & Filename
        $extension = $this->_getFileExtension();
        $filename = $this->_getFilename();

        // Path
        $path = $this->saveFolder . '/' . $filename . '.' . $extension;
        $filePath = fopen($path, 'w');

        // Get the file
        $response = $client->get($this->audioFile, ['save_to' => $filePath]);
        $status = $response->getStatusCode();
        if ($status === 200) {
            return $path;
        }

        return FALSE;
    }

    private function _generatePeaks($file)
    {
        $fileOutput = $file . '.' . $this->outputExtenstion;
        $input = $this->waveGeneratorPath . ' -f ' . $file . ' -o ' . $fileOutput;
        $process = new Process($input);

        try {
            $process->mustRun();
        } catch (ProcessFailedException $exception) {
            Log::error($exception, [
                "file" => $fileOutput
            ]);
        }
    }

    private function _getFileExtension()
    {
        return pathinfo($this->audioFile, PATHINFO_EXTENSION);
    }

    private function _getFilename()
    {
        return pathinfo($this->audioFile, PATHINFO_FILENAME);
    }

}
