<?php
//require __DIR__ . '/vendor/autoload.php';




namespace App\Services;

use Illuminate\Support\Facades\Log;
use YoutubeDl\YoutubeDl;
use YoutubeDl\Exception\CopyrightException;
use YoutubeDl\Exception\NotFoundException;
use YoutubeDl\Exception\PrivateVideoException;


class AfreecaService
{

    public function getVodList()
    {
        $base_url = "http://bjapi.afreecatv.com/api/minhee3769/vods?field=contents&page=";
        for ($i = 1; $i < 13; $i++) {
            $curl = curl_init();

            curl_setopt_array($curl, array(
                CURLOPT_URL => $base_url . $i,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "GET",
                CURLOPT_HTTPHEADER => array(
                    "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
                    "Accept-Encoding: gzip, deflate, br",
                    "Accept-Language: zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-TW;q=0.6,ja;q=0.5",
                    "Cache-Control: no-cache",
                    "Connection: keep-alive",
                    "Referer: https://www.bilibili.com",
                    "Pragma: no-cache",
                    "Sec-Fetch-Mode: navigate",
                    "Sec-Fetch-Site: none",
                    "Sec-Fetch-User: ?1",
                    "Upgrade-Insecure-Requests: 1",
                    "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36",
                    "cache-control: no-cache"
                ),
            ));

            $response = curl_exec($curl);
            $err = curl_error($curl);

            curl_close($curl);

            if ($err) {
                echo "cURL Error #:" . $err;
            } else {
                $content = json_decode($response, true);
                foreach ($content["data"] as $item) {
                    echo "http://vod.afreecatv.com/PLAYER/STATION/" . $item["title_no"] . "\n";
                    self::downloadVideo("http://vod.afreecatv.com/PLAYER/STATION/" . $item["title_no"] );
                }
            }
//            $listContent = file_get_contents($base_url . $i);
//            $content = json_decode($listContent, true);
//            $data = $content["data"];
//            foreach ($data as $item) {
//                echo "http://vod.afreecatv.com/PLAYER/STATION/" . $item["45082989"] . "\n";
//            }

        }
    }

    public function downloadVideo($url)
    {
        $dl = new YoutubeDl([
            'continue' => true, // force resume of partially downloaded files. By default, youtube-dl will resume downloads if possible.
//            'format' => 'bestvideo',
        ]);
        // For more options go to https://github.com/rg3/youtube-dl#user-content-options

        $dl->setDownloadPath('/Volumes/intel660p/video/live/afreeca');
        // Enable debugging
        $dl->debug(function ($type, $buffer) {
            if (\Symfony\Component\Process\Process::ERR === $type) {
                echo 'ERR > ' . $buffer;
            } else {
                echo 'OUT > ' . $buffer;
            }
        });
        $dl->onProgress(function ($progress) {
            $percentage = $progress['percentage'];
            $size = $progress['size'];
            $speed = $progress['speed'] ?? null;
            $eta = $progress['eta'] ?? null;

            echo "Percentage: $percentage; Size: $size";
            if ($speed) {
                echo "; Speed: $speed";
            }
            if ($eta) {
                echo "; ETA: $eta";
            }
            // Will print: Percentage: 21.3%; Size: 4.69MiB; Speed: 4.47MiB/s; ETA: 00:01
        });
        try {
            $video = $dl->download($url);
            echo $video->getTitle(); // Will return Phonebloks
            // $video->getFile(); // \SplFileInfo instance of downloaded file
        } catch (NotFoundException $e) {
            // Video not found
            Log::error($e->getTraceAsString());
        } catch (PrivateVideoException $e) {
            // Video is private
            Log::error($e->getTraceAsString());
        } catch (CopyrightException $e) {
            // The YouTube account associated with this video has been terminated due to multiple third-party notifications of copyright infringement
        } catch (\Exception $e) {
            // Failed to download
            Log::error($e->getTraceAsString());
        }

    }

}
