<?php

namespace App\Http\Controllers;

use App\Models\Download;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class ApplicationController extends Controller
{
    public function main() {
        $downloads = Download::orderByRaw("FIELD(status , 'in_progress', 'pending', 'in_error', 'completed') ASC")->orderBy('created_at', 'desc')->get();

        /*foreach($downloads as $download) {
            if($download->status == 'pending' || $download->status == 'in_progress') {
                // search file process
                $proc_file = storage_path('temp/proc_'.$download->uniqid);
                if(is_readable($proc_file)) {
                    $infos = json_decode(file_get_contents($proc_file));
                    $download->progress_value = $infos->progress;
                }
            }
        }*/

        return response()->json([
            'status' => 'success',
            'downloads' => $downloads
        ]);
    }

    private function liveExecuteCommand(Download $download, $cmd)
    {
        while (@ ob_end_flush()); // end all output buffers if any

        $proc = popen("$cmd && echo FINISH", 'r');

        while ($line = fgets($proc))
        {
            $line = preg_replace("/\s+/", " ", $line);
            $parts = explode(' ', $line);
            echo '<span style="color: red;">'.print_r($parts, true).'</span><br/>';
            if(count($parts) > 1) {
                if($parts[0] == '[download]') {

                    if($parts[1] == 'Destination:') {
                        $download->name = str_replace('_', ' ', substr(basename($parts[2]), 0, strrpos(basename($parts[2]), '.')));
                        echo "Title => " . $download->name;
                    } else {
                        echo "Progress => " . $parts[1];
                        $progress = floatval($parts[1]);
                        if($progress >= 100) {
                            $download->progress_value = 100;
                            $download->status = 'completed';
                        } else {
                            $download->status = 'in_progress';
                            $download->progress_value = ceil($progress);
                        }

                        $download->save();
                        DB::commit();
                    }
                }
            }
            echo "<br/>";
            @flush();
        }

        pclose($proc);
    }

    public function process($name){
        $download = Download::where('uniqid', $name)->first();
        if($download) {
            $url = 'https://youtu.be/' . $name;
            $cmd = 'youtube-dl --newline -o "' . storage_path('files/%(title)s.%(ext)s') . '" --extract-audio -x --audio-format mp3 "' . $url . '"';
            $this->liveExecuteCommand($download, $cmd);
        } else {
            echo 'No download';
        }
    }
}
