
<style>
.ssqupscale-drag-drop-area {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  border: 2px dashed #ccc;
  border-radius: 5px;
  padding: 20px;
  text-align: center;
  font-size: 16px;
  color: #666;
  cursor: pointer;
  max-width:350px;
  min-height:150px;
}

.ssqupscale-drag-drop-area .dashicons {
  font-size: 50px;
  margin-bottom: 50px;
}

.ssqupscale-drag-drop-area p {
  margin: 0;
  margin-bottom: 2rem;
}

.ssqupscale-drag-drop-area:hover {
  background-color: #f9f9f9;
}

.ssqupscale-drag-drop-area.active {
  border-color: #1e8cbe;
  background-color: #f1f1f1;
  color: #1e8cbe;
}

.ssqupscale-drag-drop-area.active .dashicons {
  color: #1e8cbe;
}

</style>



<?php 

$licenseid = freemius_scrollsequence()->_get_license() ? freemius_scrollsequence()->_get_license()->id : "none";
$installid = freemius_scrollsequence()->get_site()->id;
$year_flk = date("Y");
$month_flk = date("m");
$timestamp = time();

$filekey = $year_flk.'-'.$month_flk.'/lic-'.$licenseid.'-ins-'.$installid.'-ts-'.$timestamp;

?>



<h3>AI Upscale</h3>
<p>Upload video and the tool resize the input video to 2K resolution.</p>
<p>Suitable for cases when you have a low quality video. </p>
<p></p>




<section>
    <div class="ssqupscale-drag-drop-area">
        <div class="dashicons dashicons-upload"></div>
        <p>Drag and drop your <strong>video</strong> file here or click to select a file.</p>
        <input 
            type="file" 
            id="ssqupscale-video-file" 
            accept="video/*" 
            style="padding-left:1rem; padding-right:2rem;"
        />
        <div id="ssqupscale-file-alert-div" style="min-height:2rem; padding-top:1.25rem;"></div>
    </div>
    <p><i>1000 MB file size limit. First 100 seconds.</i></p>
    <div style="padding-top:2rem">
        <label for="ssqupscale-slugname" style="display:block; font-weight:bold">File prefix</label>
        <input 
            id="ssqupscale-slugname" 
            type="text" 
            maxlength="30" 
            onkeydown="return /[a-z0-9-]/i.test(event.key)" value="scrollsequence-upscale" 
        ></input>
        <i>Only charactes "a-z", "0-9" and hyphen "-" are allowed! </i>
    </div>



    <div style="padding-top:2rem">
        <input 
            type="submit" 
            name="ssqupscale-submit" 
            id="ssqupscale-submit" 
            class="button button-primary" 
            disabled 
            value="Upload Video" 
        >
    </div>

    <?php /* RESULTS  START */ ?>
    <div id="ssqupscale-results-wrap" style="visibility:hidden; min-height:500px" >
        <h3> Output </h3>

        <span id="ssqupscale-upload-progress" style="visibility:hidden;">
            <label for="ssqupscale-upload-progress-bar" style="margin-right: 10px">Uploading progress:</label>
            <progress id="ssqupscale-upload-progress-bar" value="0" max="100"> 0% </progress>
        </span>

        <p id="ssqupscale-processing-message" style="margin-bottom:1rem;"></p>


        <a href id="ssqupscale-results-button" style="visibility:hidden; margin-bottom:1rem; margin-right:2rem;" class="button button-primary" target="_blank">Download Video </a>
    </div>

    <?php /* RESULTS  END */ ?>




</section>

<?php if (freemius_scrollsequence()->is_plan_or_trial__premium_only('BUSINESS', true)) { ?>

    <script>
    (function () {
        /*

        This function is not developed yet due to high GPU cost.
        Contact Scrollsequence if you are interested in turning on this feature experimentally on your install. 

        
        */
        // Define vars
        let DBG=true;
        const dragDropArea = document.querySelector('.ssqupscale-drag-drop-area');
        const videoFileInput = document.querySelector('#ssqupscale-video-file');
        const fileAlertDiv = document.querySelector('#ssqupscale-file-alert-div');
        let videoFileVar = null

        let slugnameInput = document.querySelector('#ssqupscale-slugname');

        const submit = document.querySelector('#ssqupscale-submit');

        const uploadProgress = document.querySelector('#ssqupscale-upload-progress');
        const uploadProgressBar = document.querySelector('#ssqupscale-upload-progress-bar');
        const processingMessage = document.querySelector('#ssqupscale-processing-message');


        let resultsWrap = document.querySelector('#ssqupscale-results-wrap');
        let resultsButton = document.querySelector('#ssqupscale-results-button');

        let waitingTime = 0;

        // DRAG AND DROP AREA 
        dragDropArea.addEventListener('dragover', (event) => {
            event.preventDefault();
            dragDropArea.classList.add('active');
        });
        dragDropArea.addEventListener('dragleave', () => {
            dragDropArea.classList.remove('active');
        });
        dragDropArea.addEventListener('drop', (event) => {
            event.preventDefault();
            if (videoFileInput.disabled === !true){
                dragDropArea.classList.remove('active');
                videoFileVar = event.dataTransfer.files[0];
                DBG&&console.log('drop!',videoFileVar);
                checkFileInput(videoFileVar)
            }
        });
        // FILE INPUT AREA
        videoFileInput.addEventListener('change', () => {
            videoFileVar = videoFileInput.files[0];
            DBG&&console.log('change!', videoFileVar);
            checkFileInput(videoFileVar)
        });
        // CHECK FILE INPUT 
        function checkFileInput(videoFileVar){
            DBG&&console.log('checkFileInput() videoFileVar:',videoFileVar)
            
            if (videoFileVar.size > 1000000 * 1000) { // Check size 
                alert('Error: File size too large')
                fileAlertDiv.innerHTML = 'Error, File size too large';
                fileAlertDiv.style.color = "red"
                submit.disabled=true;
            } else if ( videoFileVar.type.includes("video") ){
                fileAlertDiv.innerHTML = 'File Accepted';
                fileAlertDiv.style.color = "green"
                submit.disabled=false;
            } else {
                alert('Error: Please select a video file')
                fileAlertDiv.innerHTML = 'Error: Please select a video file';
                fileAlertDiv.style.color = "red"
                submit.disabled=true;
            }
        }

        // FORM SUBMIT
        submit.addEventListener('click', ()=> { ssqupscaleHandleSubmit() } ); 
        async function ssqupscaleHandleSubmit(){
            DBG&&console.log('ssqupscaleHandleSubmit')
            // STATE 
            videoFileInput.disabled=true;
            slugnameInput.disabled=true;


            submit.disabled=true;


            resultsWrap.style.visibility="visible";

            // 1 GET PRESIGNED URL
            const response = await fetch(
                '<?php echo $SCROLLSEQUENCEAPIROOT; ?>/media-upscale-upload/',
                {
                    method: 'POST',
                    headers: {
                    'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ 
                        // VERY IMPORTANT, VERY HARD TO CHANGE AFTER RELEASE OF SSQ 1.5.0
                        version: "<?php echo SCROLLSEQUENCE_VERSION; ?>",
                        licenseid: "<?php echo $licenseid; ?>",
                        installid: "<?php echo $installid; ?>",
                        filekey: '<?php echo $filekey; ?>', 
                        originalfilename: videoFileVar.name,
                        originalfileext: videoFileVar.name.substr(videoFileVar.name.lastIndexOf('.')+1,videoFileVar.name.length),
                        slugname: slugnameInput.value,
                        //quality: document.querySelector('input[name="ssqconvert_quality_radio"]:checked').value,
                        //downscale: document.querySelector('input[name="ssqconvert_downscale_radio"]:checked').value,
                    }),
                }
            )      

            if (response.ok) {
                DBG&&console.log('response.ok')
                const responseJson = await response.json()
                
                if (responseJson.error){
                    alert(responseJson.error) // this is my custom error message from plugin
                    return;
                } else {
                    // STATE 
                    uploadProgress.style.visibility="visible"
                    // REQUEST TO S3
                    var xhr = new XMLHttpRequest();
                    xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4) {
                        if (xhr.status === 200) {
                            alert('Upload successful!')
                            uploadProgress.style.accentColor="gray"

                            runUpscaleJob()
                        }
                        else {
                            console.error('S3 Upload Error:', uploadResponse)
                            alert('Upload failed.')
                            uploadProgress.style.visibility="hidden"
                            submit.disabled=false;
                        }
                    }
                    };
                    xhr.upload.onprogress = function(e) {
                        if (e.lengthComputable) {
                            var percentComplete = (e.loaded / videoFileVar.size) * 100;
                            //console.log('percentComplete:',percentComplete)
                            uploadProgressBar.value=percentComplete
                            uploadProgressBar.innerHTML=percentComplete+"%"
                        }
                    };
                    xhr.open("PUT", responseJson.url);
                    xhr.send(videoFileVar);
                }
                
            } else {
                DBG&&console.log('response NOT OK')
                alert('ERROR: Failed to get pre-signed URL.')
            } 
        }

        async function runUpscaleJob(){
            console.log('runUpscaleJob()',)
            // POST JOB REQUEST
            const jobResponse = await fetch(
                '<?php echo $SCROLLSEQUENCEAPIROOT; ?>/media-upscale-runjob/',
                {
                    method: 'POST',
                    headers: {
                    'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ 
                        // VERY IMPORTANT, VERY HARD TO CHANGE AFTER RELEASE OF SSQ 1.5.0
                        version: "<?php echo SCROLLSEQUENCE_VERSION; ?>",
                        licenseid: "<?php echo $licenseid; ?>",
                        installid: "<?php echo $installid; ?>",
                        filekey: '<?php echo $filekey; ?>', 
                        originalfileext: videoFileVar.name.substr(videoFileVar.name.lastIndexOf('.')+1,videoFileVar.name.length),
                        //slugname: slugnameInput.value,
                    }),
                }
            )      

            if (jobResponse.ok) {
                DBG&&console.log('jobResponse.ok')
                const responseJson = await jobResponse.json()
                const jobId=JSON.parse(responseJson.response).id

                if (responseJson.error){
                    alert(responseJson.error) // this is my custom error message from plugin
                    return;
                } else {
                    console.log('successfull response from run job: ', responseJson)
                    processingMessage.innerHTML = "Job Status: Submitted";
                    checkUpscaleJob(jobId)

                }
            } else {
                DBG&&console.log('response NOT OK')
                alert('ERROR: Failed to get run a Frame Former job.')
            }             
        }

        
        async function checkUpscaleJob(jobId){
            const jobStatusResponse = await fetch(
                '<?php echo $SCROLLSEQUENCEAPIROOT; ?>/media-upscale-checkjob/',
                {
                    method: 'POST',
                    headers: {
                    'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ 
                        // VERY IMPORTANT, VERY HARD TO CHANGE AFTER RELEASE OF SSQ 1.5.0
                        jobId: jobId,
                    }),
                }
            )      
            if (jobStatusResponse.ok) {
                DBG&&console.log('jobStatusResponse.ok')
                const responseCheckJson = await jobStatusResponse.json()

                if (responseCheckJson.error){
                    alert(responseCheckJson.error) // this is my custom error message from plugin
                    return;
                } else {
                    console.log('XXX successfull response from checkjob: ', responseCheckJson)
                    if (responseCheckJson.status === "COMPLETE"){
                        processingMessage.innerHTML = "Job Status: Complete";    
                        console.log('XXXXXXXXXX JOB COMPLETE!!!! ')
                        showResults()
                    } else if (responseCheckJson.status === "ERROR"){
                        console.log('XXXXXXXXXX JOB ERROR!!!! ')
                        processingMessage.innerHTML = "Job Status: ERROR";    
                    } else {            
                        processingMessage.innerHTML = "Job Status: Processing";            
                        checkUpscaleJob(jobId)
                    }
                }
            } else {
                DBG&&console.log('response NOT OK')
                alert('ERROR: Failed to check  a Frame Former job.')
            }            
        }
        


        
        function showResults(){
            console.log('showResults()')
            resultsButton.href="https://scrollsequence-media-frameformer-v1-out.s3.eu-west-1.amazonaws.com/v1/<?php echo $filekey; ?>/"+slugnameInput.value+"_60fps.mp4";
            resultsButton.style.visibility="visible";

        }
        

        function pad(num, size) {
            let s = num + "";
            while (s.length < size) s = "0" + s;
            return s;
        }
    })();
    </script>
<?php } else { ?>
    <script>
        (function () {
            const submitButton = document.querySelector('#ssqupscale-submit');
            submitButton.disabled=false; 

            submitButton.addEventListener('click', ()=> { ssqupscaleHandleSubmit() } ); 
            function ssqupscaleHandleSubmit(){
                if (confirm("Frame Former is available on Business plans only. Do you wish to continue?")) {
                    window.location.href = "<?php echo admin_url( 'admin.php?page=scrollsequence-dashboard-pricing&trial=true' ) ?>";
                }
            }
        })();
    </script>
<?php } ?>

