<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Video_player extends CI_Controller {

    public function __construct() {
        parent::__construct();

        $this->load->library('tt_video_converter');
    }

    public function show_player() {
        $this->load->view('video_player/index');
    }

    public function show_plyr() {
        $this->load->view('video_player/custom_plyr');
    }

    public function upload_video() {
        ini_set('max_execution_time', 7200);
        if (isset($_FILES['video_file']['name'])) {
            $upload_path = './content-library/test-video/';
            $config['upload_path'] = $upload_path;
            $config['allowed_types'] = 'wmv|mp4|avi|webm|3gp|flv';
            $config['max_size'] = 0;
            $config['max_file_name'] = 200;
            $config['encrypt_name'] = TRUE;

            if (!is_dir($upload_path)) {
                mkdir($upload_path, 0777);
            }

            $this->load->library('upload', $config);

            if (!$this->upload->do_upload('video_file')) {
                echo $this->upload->display_errors();
            } else {
                // $this->process_file($data);
                $this->cf->dd($this->upload->data());
                $time_start = microtime(true);
                $test_output = $this->tt_video_converter->set_file($this->upload->data())
                                ->convert_video()->get_converted_files_name()->check_converted_video()->get_full_report();
                $time_end = microtime(true);
                $data['output'] = $test_output;
                $data['output']['conversion_time'] = $time_end - $time_start;
                $data['output']['total_required_time'] = time() - filter_input(INPUT_SERVER, 'REQUEST_TIME');
                echo $this->load->view('video_player/plyr', $data, TRUE);
            }
        }
    }

    public function process_file($status) {
        $time_start = microtime(true);
        $input_file = $this->upload->data();
        if ($input_file['file_ext'] == '.mp4') {
            $output_file = str_replace($input_file['file_ext'], '_converted.mp4', $input_file['full_path']);
        } else {
            $output_file = str_replace($input_file['file_ext'], '.mp4', $input_file['full_path']);
        }
        $data['converted_file'] = str_replace($input_file['file_ext'], '.mp4', $input_file['file_name']);
        $temp_file_path = str_replace($input_file['file_ext'], '.txt', $input_file['full_path']);
        $video_info = $this->get_video_info($input_file['full_path'], $temp_file_path);
        if ($video_info->format->probe_score != 100) {
            $status['upload_format'] = 'Problem with video file format';
        } else {
            $status['prob_score'] = 'ok';
            $status['conversion_status'] = $this->convert_file($input_file['full_path'], $output_file);
            $converted_video_info = $this->get_video_info($output_file, $temp_file_path);
            $status = $this->check_converted_file($video_info, $converted_video_info, $status);
            $time_end = microtime(true);
            $status['required_time_for_conversion'] = $time_end - $time_start;
            $status['video_info'] = $video_info;
            $status['converted_video_info'] = $converted_video_info;
        }
        $data['status'] = $status;
        echo $this->load->view('video_player/plyr', $data, TRUE);
    }

    public function get_video_info($input_file, $temp_file) {
        // This is for live server $command = '/usr/local/bin/ffprobe -i ' . $input_file . ' -v quiet -print_format json -show_format > ' . $temp_file . ' 2>&1';

        $command = 'ffprobe -i ' . $input_file . ' -v quiet -print_format json -show_format -show_streams > ' . $temp_file . ' 2>&1';
        exec($command, $output, $status);
        $video_info = json_decode(file_get_contents($temp_file));
        unlink($temp_file);
        return $video_info;
    }

    public function convert_file($input_file, $output_file) {
        // 480p with 500k bit rate, frame rate 20
        //$command = 'ffmpeg -i '.$input_file.' -codec:v libx264 -profile:v high -b:v 500k -maxrate 500k -bufsize 1000k -r 20 -crf 18 '.$output_file.' 2>&1';
        // 480p with 1000k bit rate, frame rate default (15)
        //$command = 'ffmpeg -i '.$input_file.' -codec:v libx264 -profile:v high -b:v 1000k -maxrate 1000k -bufsize 1000k '.$output_file.' 2>&1';
        // 720p with 500k bit rate, frame rate 20
        //$command = 'ffmpeg -i '.$input_file.' -codec:v libx264 -profile:v high -b:v 500k -maxrate 500k -bufsize 1000k -vf: scale=-1:720 -r 20 -crf 18 '.$output_file.' 2>&1';
        // 720p with 1000k bit rate, frame rate 20
        $command = 'ffmpeg -i ' . $input_file . ' -codec:v libx264 -profile:v high -b:v 1000k -maxrate 1000k -bufsize 2000k -vf: scale=-1:720 -r 20 -crf 18 ' . $output_file . ' 2>&1';

        // 720p with 1000k bit rate, frame rate 30
        //$command = 'ffmpeg -i '.$input_file.' -codec:v libx264 -profile:v high -b:v 1000k -maxrate 1000k -bufsize 2000k -vf: scale=-1:720 -r 30 -crf 18 '.$output_file.' 2>&1';
        // 1080p with 1500k bit rate, frame rate 20
        //$command = 'ffmpeg -i '.$input_file.' -codec:v libx264 -profile:v high -b:v 1500k -maxrate 1500k -bufsize 2000k -vf: scale=-1:1080 -r 20 -crf 18 '.$output_file.' 2>&1';
        // 1080p with 3000k bit rate, frame rate 20
        //$command = 'ffmpeg -i '.$input_file.' -codec:v libx264 -profile:v high -b:v 3000k -maxrate 3000k -bufsize 2000k -vf: scale=-1:1080 -r 20 -crf 18 '.$output_file.' 2>&1';
        // 1080p with 3000k bit rate, frame rate 30
        //$command = 'ffmpeg -i '.$input_file.' -codec:v libx264 -profile:v high -b:v 3000k -maxrate 3000k -bufsize 2000k -vf: scale=-1:1080 -r 30 -crf 18 '.$output_file.' 2>&1';

        exec($command, $output, $status);
        if (($status == 0) && file_exists($output_file)) {
            return 'ok';
        } else {
            echo 'conversion error';
            $this->cf->dd($output);
            return 'conversion error';
        }
    }

    public function check_converted_file($video_info, $converted_video_info, $report) {
        if ($converted_video_info->format->probe_score === 100) {
            $report['converted_probe_score'] = 'ok';
        } else {
            $report['converted_probe_score'] = 'failed';
        }

        if ($video_info->format->duration == $converted_video_info->format->duration) {
            $report['duration_check'] = 'ok';
        } else {
            $report['duration_check'] = 'failed';
        }
        return $report;
    }

//    public function run_conversion() {
//        ini_set('max_execution_time', 0);
//        $this->load->library('tt_video_converter');
//        $this->run_post_video_conversion();
//        echo 'post conversion done';
//    }
//
//    public function run_post_video_conversion() {
//        $all_post_data = $this->db->select('*')->from('tbl_post')
//                        ->where('post_type', 5)->get()->result();
//
//        foreach ($all_post_data as $post_data) {
//            $profile_url = $this->get_profile_url($post_data->posted_by);
//            $full_file_path = FCPATH . 'content-library/' . $profile_url . '/' . $post_data->post_details;
//            if (file_exists($full_file_path)) {
//                $file_path = implode('/', array_map('trim', explode('/', $post_data->post_details)));
//                $file_path = str_replace(' ', '-', $file_path);
//                $file_detail = $this->prepare_file_detail($profile_url, $file_path);
//                $conversion_data = $this->convert_video($file_detail);
//                $this->update_post_video_path_in_db($conversion_data['output_file_path'], $profile_url, $post_data);
//                //$this->cf->dd($conversion_data['output_file_path']);
//            }
//        }
//    }
//
//    public function update_post_video_path_in_db($converted_file_path, $profile_url, $post_data) {
//        $replace_string = FCPATH . 'content-library/' . $profile_url . '/';
//        $data['post_details'] = trim(str_replace($replace_string, '', $converted_file_path));
//        // $this->cf->dd($post_data);
//        $this->db->where('post_id', $post_data->post_id);
//        $this->db->update('tbl_post', $data);
//        // $this->cf->dd($data);
//    }
//
//    public function prepare_file_detail($profile_url, $file_path) {
//        $path_segments = explode('/', $file_path);
//        $file_name = array_pop($path_segments);
//        $file_name_parts = explode('.', $file_name);
//        $file_detail['file_name'] = $file_name;
//        $file_detail['file_ext'] = '.' . array_pop($file_name_parts);
//        $file_detail['full_path'] = FCPATH . 'content-library/' . $profile_url . '/' . $file_path;
//        $file_detail['file_path'] = str_replace($file_detail['file_name'], '', $file_detail['full_path']);
//        return $file_detail;
//    }
//
//    public function convert_video($file_detail) {
//        $time_start = microtime(true);
//        $test_output = $this->tt_video_converter->set_file($file_detail)
//                        ->convert_video()->check_converted_video()->get_full_report();
//        $time_end = microtime(true);
//        $test_output['required_conversion_time'] = $time_end - $time_start;
//        return $test_output;
//    }
//
//    public function get_profile_url($person_id) {
//        $result = $this->db->select('url')->from('tbl_url AS tu')->join('tbl_person AS tp', 'tp.url_id = tu.url_id')
//                        ->where('tp.person_id', $person_id)->get()->row();
//        return $result->url;
//    }
    public function show_converter(){
        $data['video_course'] = $this->get_all_video_course();
        $this->load->view('video_player/convert_video', $data);
        
    }

    public function run_conversion($video_management_id) {
        ini_set('max_execution_time', 0);        
        $video_data = $this->get_all_video($video_management_id);
        $this->cf->dd($video_data);
        foreach ($video_data AS $video) {
            $path_segments = explode('/', $video->upload_video_location);
            $file_detail['file_name'] = array_pop($path_segments);
            $file_name_parts = explode('.', $file_detail['file_name']);
            $file_detail['file_ext'] = '.' . array_pop($file_name_parts);
            $file_detail['full_path'] = FCPATH . 'content-library/' . 'talhatraining' . $video->upload_video_location;
            $file_detail['file_path'] = str_replace($file_detail['file_name'], '', $file_detail['full_path']);
            if (file_exists($file_detail['full_path']) && ($file_detail['file_ext'] != '.mp4') ) {
                $this->convert_to_720p($file_detail['full_path'], $file_detail['file_ext'], $video); 
                echo $video->upload_video_id.'<br><hr>';
            }
        }
    }

    public function convert_to_720p($file_path, $file_ext, $video) {
        $output_file_path = str_replace($file_ext, '_converted_720p.mp4', $file_path);

        $command = 'ffmpeg -i ' . $this->input_file_path . ' -y -codec:v libx264 -profile:v high -b:v 1000k -maxrate 1000k -bufsize 2000k -vf: scale=-2:720 -r 24 -crf 18 -pix_fmt yuv420p ' . $this->output_file_path . ' 2>&1';
        //$this->cf->dd($command);
        exec($command, $output, $status);
        if (($status == 0) && file_exists($output_file_path)) {            
            $save_path = str_replace(FCPATH . 'content-library/' . 'talhatraining', '', $output_file_path);
            $data['upload_video_location'] = $save_path;
            $this->db->where('upload_video_id', $video->upload_video_id);
            $this->db->update('tbl_upload_video', $data);
            unlink($file_path);            
        } else {
            $this->cf->dd($output);
        }
    }

    public function get_all_video($id) {
        $result = $this->db->select('*')
                       ->from('tbl_upload_video')
                       ->where('video_management_id', $id)
                       ->get()->result();
        return $result;
    }
    
    public function get_all_video_course(){
        $result = $this->db->select('*')->from('tbl_video_management')->get()->result();
        return $result;
    }

}
