<?php

namespace App\Console\Commands;

use App\TelegramBot\Api;
use Illuminate\Console\Command;

class abook extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'abook';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    //$

    public function handle()
    {
        $api = new Api(0,"1298254718:AAGPzl98t7QBToy0uV9Fi7NrXZnQ84DTKYA");


        $message_id = $api->execute("sendMessage",[
            "chat_id" => 1250349080,
            "text" => "Подключение к архиву.."
        ])->result->message_id;
        sleep(1);

        $link = "https://knigavuhe.org/book/zhit-iz-osnovy-bytija/";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36"
        ));
        curl_setopt($ch, CURLOPT_URL, $link);
        $result = curl_exec($ch);
        curl_close($ch);




        $json = $this->getElementValue($result,'*/
  var player = new BookPlayer(',');');

        $json = $this->getElementValue($json,', ',', [{"label"');
        $audio_list = json_decode($json);

        $dir_name = "/var/www/html/booksbot/storage/".$this->generateRandomString();



        if(mkdir($dir_name, 0777, true)) {

            $api->execute("editMessageText",[
                "chat_id" => 1250349080,
                "message_id" => $message_id,
                "text" => "Подготовка файлов..\n\n`0%`"
            ]);
            $count = count($audio_list);

            $i=0;
            $progress_txt = "";
            foreach ($audio_list as $item) {
                file_put_contents("{$dir_name}/{$item->id}.mp3",file_get_contents($item->url));
                $filesize = filesize("{$dir_name}/{$item->id}.mp3");
                if($filesize>41943040){
                    echo "\n\n{$dir_name}/{$item->id}.mp3\n\n";
                    exec("ffmpeg -i {$dir_name}/{$item->id}.mp3 -f segment -segment_time 900 -c copy {$dir_name}/{$item->id}%03d.mp3");
                    unlink("{$dir_name}/{$item->id}.mp3");
                }

                $i ++;
                $progress_txt .= "█";
                $percent = round(100/$count*$i);

                $api->execute("editMessageText",[
                    "chat_id" => 1250349080,
                    "message_id" => $message_id,
                    "text" => "Подготовка файлов..\n\n`{$progress_txt} {$percent}%`"
                ]);
            }
        }

        $files = array_slice(scandir($dir_name),2);

        $api->execute("deleteMessage",[
            "chat_id" => 1250349080,
            "message_id" => $message_id,
        ]);

        foreach ($files as $file) {
            echo "{$dir_name}/{$file}\n";
            $api->execute("sendAudio",[
                "chat_id" => 1250349080,
                "audio" => new \CURLFile("{$dir_name}/{$file}")
            ]);
        }

        echo $json;

    }


    function generateRandomString($length = 10) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }

    public function getElementValue($string,$strStart,$strEnd){
        $str_search = strpos($string,$strStart);
        if($str_search===false){
            return false;
        }
        $str_1 = substr($string,$str_search+strlen($strStart));
        $str_search = strpos($str_1,$strEnd);
        $res = substr($str_1,0,$str_search);
        return $res;
    }
}
