
<style>
.ssqframeformer-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;
}

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

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

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

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

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

</style>


<?php 

$scrollsequence_licenseid = freemius_scrollsequence()->_get_license() ? freemius_scrollsequence()->_get_license()->id : "none";
$scrollsequence_installid = freemius_scrollsequence()->get_site()->id;
$scrollsequence_year_flk = date("Y");
$scrollsequence_month_flk = date("m");
$scrollsequence_timestamp = time();

$filekey = $scrollsequence_year_flk.'-'.$scrollsequence_month_flk.'/lic-'.$scrollsequence_licenseid.'-ins-'.$scrollsequence_installid.'-ts-'.$scrollsequence_timestamp;

?>



<h3>
    <?php _e( 'Frame Former', 'scrollsequence' ); ?>
    <div class="ssqtooltip">
        <span class="dashicons  dashicons-editor-help"></span>
        <span class="ssqtooltiptext">
            <?php _e( 'Upload video and the tool will form new frames using AWS Elemental Media Convert Frame Former. Suitable for cases when you have a low framerate video, or want to make your animations smoother.', 'scrollsequence' ); ?>
        </span>
    </div>    
</h3>



<section>
    <div class="ssqframeformer-drag-drop-area" style="margin-left:1rem;">
        <div class="dashicons dashicons-upload"></div>
        <p> <?php _e( 'Drag and drop your video file here or click on "Choose File" button.', 'scrollsequence' ); ?></p>
        <input 
            type="file" 
            id="ssqframeformer-video-file" 
            accept="video/*" 
            style="padding-left:1rem; padding-right:2rem;"
        />
        <div id="ssqframeformer-file-alert-div" style="min-height:2rem; padding-top:1.25rem;"></div>
    </div>
    <p style="margin-left:2rem;" ><i> <span  class="dashicons dashicons-database"></span> 1GB  <span style="margin-left:2rem;" class="dashicons dashicons-video-alt2"></span> 100 <?php _e( 'seconds', 'scrollsequence' ); ?> </i></p>
    <div style="padding-top:2rem">
        <label for="ssqframeformer-slugname" style="display:block; font-weight:bold; margin-bottom:0.5rem;">
            <?php _e( 'File prefix', 'scrollsequence' ); ?>
            <div class="ssqtooltip">
                <span class="dashicons  dashicons-editor-help"></span>
                <span class="ssqtooltiptext">
                    <?php _e( 'Only charactes &quot;a-z&quot;, &quot;0-9&quot; and hyphen &quot;-&quot; are allowed!', 'scrollsequence' ); ?>
                </span>
            </div>    
        </label>
        <input 
            id="ssqframeformer-slugname" 
            type="text" 
            maxlength="30" 
            onkeydown="return /[a-z0-9-]/i.test(event.key)" value="my-scrollsequence" 
            style="margin-left:1rem;"
        ></input>
    </div>



    <div style="padding-top:2rem;margin-left:1rem;">
        <button id="ssqframeformer-submit" class="button button-primary" disabled style="font-size:14px; line-height:unset!important;"  >
            <span class="dashicons dashicons-cloud-upload" ></span>
            <?php _e( 'Upload Video', 'scrollsequence' ); ?>
        </button>
    </div>

    <?php /* RESULTS  START */ ?>
    <div id="ssqframeformer-results-wrap" style="visibility:hidden; min-height:500px" >
        <h3> 
            <?php _e( 'Output', 'scrollsequence' ); ?> 
            <div class="ssqtooltip">
                <span class="dashicons  dashicons-editor-help"></span>
                <span class="ssqtooltiptext">
                    <?php _e( 'Source video is converted to 60FPS.', 'scrollsequence' ); ?>
                </span>
            </div>    
        </h3>

        <span id="ssqframeformer-upload-progress" style="visibility:hidden;margin-left:1rem;">
            <label for="ssqframeformer-upload-progress-bar" style="margin-right: 10px"><?php _e( 'Upload Progress', 'scrollsequence' ); ?>: </label>
            <progress id="ssqframeformer-upload-progress-bar" value="0" max="100"> 0% </progress>
        </span>

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


        <a href id="ssqframeformer-results-button" style="visibility:hidden; margin-bottom:1rem; margin-right:2rem;margin-left:1rem;" 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 () {
        // Define vars
        let DBG=true;
        const dragDropArea = document.querySelector('.ssqframeformer-drag-drop-area');
        const videoFileInput = document.querySelector('#ssqframeformer-video-file');
        const fileAlertDiv = document.querySelector('#ssqframeformer-file-alert-div');
        let videoFileVar = null

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

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

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

        let resultsWrap = document.querySelector('#ssqframeformer-results-wrap');
        let resultsButton = document.querySelector('#ssqframeformer-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', ()=> { ssqFrameFormerHandleSubmit() } ); 
        async function ssqFrameFormerHandleSubmit(){
            DBG&&console.log('ssqFrameFormerHandleSubmit')
            // 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-frameformer-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 $scrollsequence_licenseid; ?>",
                        installid: "<?php echo $scrollsequence_installid; ?>",
                        filekey: '<?php echo $filekey; ?>', 
                        originalfilename: videoFileVar.name,
                        originalfileext: videoFileVar.name.substr(videoFileVar.name.lastIndexOf('.')+1,videoFileVar.name.length),
                        slugname: slugnameInput.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"

                            runFrameformerJob()
                        }
                        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 runFrameformerJob(){
            console.log('runFrameformerJob()',)
            // POST JOB REQUEST
            const jobResponse = await fetch(
                '<?php echo $SCROLLSEQUENCEAPIROOT; ?>/media-frameformer-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 $scrollsequence_licenseid; ?>",
                        installid: "<?php echo $scrollsequence_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()
                
                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";
                    checkFrameFormerJob(responseJson.jobId)

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

        async function checkFrameFormerJob(jobId){
            const jobStatusResponse = await fetch(
                '<?php echo $SCROLLSEQUENCEAPIROOT; ?>/media-frameformer-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";            
                        setTimeout(function() {
                            checkFrameFormerJob(jobId);
                        }, 1000);
                    }
                }
            } 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('#ssqframeformer-submit');
            submitButton.disabled=false; 

            submitButton.addEventListener('click', ()=> { ssqFrameFormerHandleSubmit() } ); 
            function ssqFrameFormerHandleSubmit(){
                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 } ?>

