<?php

namespace App\Http\Controllers;

use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Jenssegers\Agent\Agent;
use OpenTok\MediaMode;
use OpenTok\OpenTok;

use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use OpenTok\ArchiveMode;
use OpenTok\OutputMode;

class VideoTestController extends Controller
{
    public function index(){
        
        $opentok = new OpenTok(config('app.opentokApiKey'),config('app.opentokApiSecret'));
        $otSession = $opentok->createSession(array('mediaMode' => MediaMode::ROUTED));
        $otSessionId = $otSession->getSessionId();
        $otToken = $opentok->generateToken($otSessionId);

        
        $step = 'webcam-test';
        $agent = new Agent();
        $allow = !$agent->isPhone() && !$agent->isTablet();

        return view('app.video.video-test', compact('otSessionId', 'otToken',  'step', 'allow'));

    }

     // get video url from archive id
     public function getArchive($archiveId)
     {
         $opentok = new OpenTok(config('app.opentokApiKey'), config('app.opentokApiSecret'));
         $archive = $opentok->getArchive($archiveId);
         while ($archive->url == null) {
             $archive = $opentok->getArchive($archiveId);
         }
         return response()->json(['video' => $archive->url]);
     }
 
     public function startRecording(Request $request, $sessionId)
     {
         $opentok = new OpenTok(config('app.opentokApiKey'), config('app.opentokApiSecret'));
         $archiveOptions = array(
             'name' => 'Recording Data',
             'hasAudio' => true,
             'hasVideo' => true,
             'outputMode' => OutputMode::COMPOSED
         );
         $archive = $opentok->startArchive($sessionId, $archiveOptions);
         $archiveId = $archive->id;
         session()->put('archive_id', $archiveId);
         return response()->json($archive);
     }
 
     public function stopRecording($archiveId)
     {
         $opentok = new OpenTok(config('app.opentokApiKey'), config('app.opentokApiSecret'));
         $archive = $opentok->stopArchive($archiveId);
         return response()->json($archive);
     }
 
     public function deleteArchive($archiveId)
     {
         $opentok = new OpenTok(config('app.opentokApiKey'), config('app.opentokApiSecret'));
         $opentok->deleteArchive($archiveId);
         return response()->json(['response' => 'archive deleted successfully']);
     }
 
     public function saveArchive(Request $request)
     {
         $opentok = new OpenTok(config('app.opentokApiKey'), config('app.opentokApiSecret'));
         $archiveId = $request->input('archiveID');
 
         $archive = $opentok->getArchive($archiveId);
 
         //If failed to get the recorded data URL, call the API again
         while ($archive->url == null) {
             $archive = $opentok->getArchive($archiveId);
         }
 
         $contents = file_get_contents($archive->url);
 
         $fileName = Str::uuid() . '_' . Carbon::now()->format('d-m-y_h-i-s-a') . '.mp4';
         $result = Storage::disk('local')->put($fileName, $contents);

         if(!$result){
             return $this->fail('Unable to save file.');
         }

         $response = $this->postFileToJava($request, $fileName, $request->input('ep') ? $request->input('ep') : null);

         if(!@$response['success']){
             return $this->fail($response['message']);
         }
 
         return $response;
     }

     private function postFileToJava($request, $fileName, $ep = null){

        $requestToPost = Http::asMultipart();

        try {
            $videoFilePath = storage_path('app/'.$fileName);
            $videoFile = fopen(config('app.storageDir') . '/' .$videoFilePath, 'r');
            $requestToPost->attach($ep ? 'file' : 'messageVideo', $videoFile, $fileName);
        } catch (\Exception $e) {
            error_log($e->getMessage() . " VIDEO PATH: " . $fileName);
        }


        $backendUrl = config('stag.backendUrl') . ($ep ? $ep : '/internalMessage/create');

        $inputs = [
            ['name'=>'toProUid', 'contents' => $request->get('toProUid')],
            ['name'=>'regardingClientUid', 'contents' => $request->get('regardingClientUid')],
            ['name'=>'regardingCompanyUid', 'contents' => $request->get('regardingCompanyUid')],
            ['name'=>'contentText', 'contents' => $request->get('contentText')],
            ['name'=> 'sessionKey', 'contents' =>  $this->performer->session_key],
        ];

        if($ep) {
            $inputs = [
                ['name'=>'purpose', 'contents' => 'webcam'],
                ['name'=> 'sessionKey', 'contents' =>  $this->performer->session_key],
            ];
        }

        $response = $requestToPost->post($backendUrl, $inputs)->json();
       
        return $response;
     }
 
     public function videoDownload($uid, Request $request)
     {
         //TODO
         return Storage::download('video-file.mp4');
     }


    public function uploadVideo(Request $request)
    {

        if ($request->hasFile('hcp_intro')) {
            $video = $request->file('hcp_intro');
            $fileName = time() . '.' . $video->getClientOriginalExtension();
            $path = $video->store(""); //, uniqid() . '.' . $request->file('hcp_intro')->getClientOriginalExtension());
          
        }

        return redirect()->back();
    }
}
