var canvas, stage, txt, str, playbackSpeed = 1,
framerate = 25, duration, capturer = null, videoArr = [], frameCount = 0 , imgArr = null,myTimer;
var frameRenderCount = 0, replay = false, videoId = 0, secondCount = 1, currentTime, videoOutputURL, imodal;
var videos = [
    /*{
        src: 'videos/360_01.mp4',
        text: {
            x: 433,
            y: 296,
            fontFaceName : "'CS\ ChatThaiUI'",
            fontSize : 18,
            font: "18px "+"'CS\ ChatThaiUI'",
            color : "rgba(255,255,255,0.8)",
            lineWidth : 500,
            lineHeight : 20,
        },
        animate : function () {
           // txt.alpha = (frame - 90) * 0.015
            if(videoDOM.currentTime > 3.6){
                txt.alpha = animateFrame * 0.015
                animateFrame++;
            }
        }

    },*/

    {
        src: 'videos/360_02.mp4',
        text: {
            x: 320,
            y: 314,
            fontFaceName : "'CS\ ChatThaiUI'",
            fontSize : 18,
            font: "18px "+"'CS\ ChatThaiUI'",
            color : "rgba(255,255,255,0.8)",
            lineWidth : 500,
            lineHeight : 20,
        },
        animate : function (frame) {
            //txt.alpha = (frame - 230) * 0.015
            if(videoDOM.currentTime > 9){
                txt.alpha = animateFrame * 0.015
                animateFrame++;
            }
        }

    },

    {
        src: 'videos/360_03.mp4',
        text: {
            x: 320,
            y: 325,
            fontFaceName : "'CS\ ChatThaiUI'",
            fontSize : 18,
            font: "18px "+"'CS\ ChatThaiUI'",
            color : "rgba(255,255,255,0.8)",
            lineWidth : 500,
            lineHeight : 20,
        },
        animate : function (frame) {
            //txt.alpha = (frame - 230) * 0.015
            if(videoDOM.currentTime > 9){
                txt.alpha = animateFrame * 0.015
                animateFrame++;
            }
        }

    },

    {
        src: 'videos/360_04.mp4',
        text: {
            x: 320,
            y: 325,
            fontFaceName : "'CS\ ChatThaiUI'",
            fontSize : 18,
            font: "18px "+"'CS\ ChatThaiUI'",
            color : "rgba(255,255,255,0.8)",
            lineWidth : 500,
            lineHeight : 20,
        },
        animate : function (frame) {
            //txt.alpha = (frame - 230) * 0.015
            if(videoDOM.currentTime > 9){
                txt.alpha = animateFrame * 0.015
                animateFrame++;
            }
        }

    },

    {
        src: 'videos/360_05.mp4',
        text: {
            x: 320,
            y: 310,
            fontFaceName : "'CS\ ChatThaiUI'",
            fontSize : 18,
            font: "18px "+"'CS\ ChatThaiUI'",
            color : "rgba(255,255,255,0.8)",
            lineWidth : 500,
            lineHeight : 20,
        },
        animate : function (frame) {
           // txt.alpha = (frame - 230) * 0.015
            if(videoDOM.currentTime > 9){
                txt.alpha = animateFrame * 0.015
                animateFrame++;
            }
        }

    },


];

/*
$.getScript('//connect.facebook.net/en_th/sdk.js', function () {

    FB.init({
        appId: '979262895558775',
        version: 'v2.10'
    });
    FB.XFBML.parse();
});
*/




function switchVideo(n) {

    videoId = n;

    if (n >= videos.length) n = 0;

    videoDOM.setAttribute("src", videos[n].src);
    videoDOM.load();

    for (var k in videos[n].text){
            //console.log("Key is " + k + ", value is " + videos[n].text[k]);
        txt[k] = videos[n].text[k]
    }

}






$( document ).ready(function() {
    init()

    swiper.on("onTransitionEnd",function (swiper) {

        //console.log(swiper.activeIndex)

        switchVideo(swiper.activeIndex)

    })

});







function init() {

    canvas = document.getElementById("video-canvas");
    stage = new createjs.Stage(canvas);

    videoDOM = document.createElement('video');


    //videoDOM.src = 'ezgif.com-resize.mp4';
    //videoDOM.load();

    videoDOM.addEventListener('ended', videoEndHandler, false);
    //videoDOM.addEventListener('seeked',videoSeekHandler,false);


    video = new createjs.Bitmap(videoDOM);
    stage.addChild(video).set({ x: 0, y: 0, alpha: 1});







    //videoDOM.play();

    /* var container = new createjs.Container();
     stage.addChild(container);*/

    //var str = "ปวงข้าพระพุทธเจ้า\n ขอน้อมเกล้าน้อมกระหม่อมรําลึกใน\n พระมหากรุณาธิคุณหาที่สุดมิได้\n ข้าพระพุทธเจ้า";
    str = "ข้าพระพุทธเจ้า บริษัท บัณฑิต เซ็นเตอร์ จำกัด";

    txt = new createjs.Text("", "", "#FFF");
    txt.text = "บริษัท บัณฑิต เซ็นเตอร์ จำกัด";
    txt.textBaseline = "middle";
    txt.textAlign = "center";
    //txt.alpha = 0;
    //txt.shadow = new createjs.Shadow("#000000", 0, 0, 30);
    txt.shadow = new createjs.Shadow("rgba(0,0,0,0.5)",0,0,10);

    //txt.x = (stage.canvas.width) / 2 + 120;

    /********/



    //txt.x = (stage.canvas.width - 550) / 2;
    stage.addChild(txt);



    switchVideo(0)


    // console.log(videoDOM.duration);


    videoDOM.addEventListener('loadedmetadata', function(){

        //alert( this.duration())
        //alert( myPlayer.duration());


        videoDOM.currentTime = this.duration - 1;

        duration = this.duration


        console.log(duration);

    })










    stage.update();

    //clickHandler()
    createjs.Ticker.addEventListener("tick", draw);

    // Set same as video sourse
    createjs.Ticker.setFPS(framerate)





/*    /!*********!/
    var per_page = 3;
    if(screen.width > 767){
        per_page = 5
    }
    if(screen.width > 1200){
        per_page = 7
    }
    var swiper = new Swiper('.swiper-container', {
        pagination: '.swiper-pagination',
        slidesPerView: per_page,
        paginationClickable: true,
        spaceBetween: 30,
        freeMode: false
    });*/












}

/*
var btnPlay = document.getElementById("play")



btnPlay.addEventListener('click', function (e) {
    e.preventDefault();
    startCapture();
}, false);*/




function startCapture() {
    canvas.style.display = 'none';
    document.body.style.pointerEvents = "none"

   /* if(simulated == false){

         capturer = new CCapture({
         verbose: false,
         display: false,
         framerate: framerate,
         motionBlurFrames: 0,
         name: "wish",
         //quality: 100,
         format: 'webm',
         workersPath: 'js/',
         });


     }else{*/

        capturer = new CCapture({
            verbose: false,
            display: false,
            framerate: framerate,
            motionBlurFrames: 0,
            name: "wish-"+Date.now(),
            //quality: 100,
            format: 'ffmpegserver',
            //workersPath: "http://27.254.156.24:8082/Canvas/3rdparty/",
            workersPath: genServer+"/Canvas/3rdparty/",
            //timeLimit: videoDOM.duration,
            //frameLimit: 0,
            //autoSaveTime: 0,
            //onProgress: function( p ) { progress.style.width = ( p * 100 ) + '%' }
        });

    // }


    //clickHandler()
    //clock()

    //console.log(videoDOM.playbackRate)

    capturing = true;
    initPreplay();
    //if (!myTimer) myTimer = setInterval(myClock, 1000);
    videoDOM.play();
    capturer.start();


}


function clickCaptured(){

    var  config = {
        id : 'md-1',
        class:'modal',
        clickOutsideToClose : false,
        closeButton : false,
        body :'<div style="text-align: center"><h3>ระบบกำลังบันทึกวิดีโอของท่าน...</h3> อาจต้องใช้เวลาประมาณ 1 - 3 นาที<br>กรุณารอสักครู่ค่ะ</div>'
    };

    imodal = new Modal(config);
    imodal.open();


    //Analytics Track
    ga('send', 'event', {
        eventCategory: campaignName,
        eventAction: 'click',
        eventLabel: "BTN Captured"
    });

     setTimeout(function () {

         startCapture();

     },1000)





}




function playVideo() {

    replay = true;
    //txt.alpha = 0;
    //videoDOM.currentTime = 0;
    initPreplay();

    videoDOM.play();

    ga('send', 'event', {
        eventCategory: campaignName,
        eventAction: 'click',
        eventLabel: "BTN Video Preview"
    });

}


function initPreplay() {

    txt.alpha = 0;
    animateFrame = 0;
    videoDOM.currentTime = 0;
    secondCount = 0;
    frameRenderCount = 0;

}



var animateFrame = 0;

function draw() {
    stage.update();
    //currentTime = videoDOM.currentTime;



    if (capturer) {
        //videoDOM.play();
        capturer.capture(canvas)
        frameRenderCount++;
        //textAnimate(frameRenderCount)
        videos[videoId].animate(frameRenderCount);
    }

    if(replay){
        //console.log(videoDOM.currentTime+" : "+frameRenderCount)
        frameRenderCount++;
        videos[videoId].animate(frameRenderCount);
    }



}



function clickHandler(pEvent) {
    videoDOM.currentTime += (1 / 25);
    //videoDOM.play();
    videoDOM.pause();
    txt.text = str;
    // TweenLite.from(txt,5, {delay: 1.5,alpha:0});
}

var simulated = false, capturing = false;

function videoEndHandler() {

    console.log('videoEndHandler at '+ frameRenderCount + " Frames")
    //this.setAttribute( 'href',  );

    if(capturing){

      //  canvas.style.display = 'none';

        if (simulated == false) {
            playbackSpeed = (frameRenderCount * 0.93) / (duration * framerate);
            console.log(playbackSpeed);
            /*
            playbackSpeed = playbackSpeed > 1 ? 1 : playbackSpeed;
            console.log(playbackSpeed);*/


            if(playbackSpeed < 0.1){

                imodal.remove();

                var  config = {
                    id : 'md-2',
                    class:'modal',
                    clickOutsideToClose : false,
                    closeButton : false,
                    body :'<div style="text-align: center">เกิดข้อผิดพลาด <br>กรุณารีเฟรฟหน้านี้แล้วลองใหม่อีดครั้ง</div>'
                            +'<div class="posi_absolute" style="top: -9px; right: -9px; width: 24px; height: 24px; border-radius: 50%; background: #FFF;"><a onclick="location.reload();" class="fco_black"><i class="material-icons f24">cancel</i></a></div>'
                };

                imodal = new Modal(config);
                imodal.open();

            }else{

                simulated = true;
                videoDOM.currentTime = 0;
                videoDOM.playbackRate = playbackSpeed;

                txt.alpha = 0;

                capturer.stop();
                capturer = true;

                /*setTimeout( ()=> {

                    startCapture();

                },1000)*/

                startCapture()
                //console.log(capturer);
                //startCapture()
            }

        } else {

            console.log("videoSave() at " + frameRenderCount + " Frames");
            videoSave();
            videoDOM.pause();
        }

    }else{

        videoDOM.pause();
        replay = false;

    }

    secondCount = 0;
    frameRenderCount = 0;


}


function videoSave() {







    //if(capturer){
    capturer.stop();
    // capturer.save();

    //console.info('----------- capturer.save ------------')
    capturer.save(showVideoLink);
    //capturer.save();

    //Reset Data
    capturer = null;
    simulated = false;
    canvas.style.display = 'block';
    document.body.style.pointerEvents = ""
    clearInterval(myTimer);
    secondCount = 0;
    videoDOM.playbackRate = 1
    myTimer = false;
    capturing = false;
}


function showVideoLink(url, size) {
    //console.info('----------- showVideoLink ------------')
   // console.info('url :: http://27.254.156.24:8082' + url);

    videoOutputURL = genServer + url;



    imodal.close();
    imodal.remove();
    imodal = undefined;

    var  config = {
        id : 'md-1',
        class:'modal',
        clickOutsideToClose : false,
        closeButton : false,
        body :
        '<div class="f28 pad16-0 fco_black" style="text-align: center">ขั้นตอนที่ ๓ ดาวน์โหลดวิดีโอของท่าน</div>'+
		'<div class="posi_absolute" style="top: -9px; right: -9px; width: 24px; height: 24px; border-radius: 50%; background: #FFF;"><a onclick="location.reload();" class="fco_black"><i class="material-icons f24">cancel</i></a></div>'+
        '<div class="mdl-grid" >  <a onclick="downloadVideo(this)" style=" max-width: 300px; margin: 20px auto;font-size: 1.5em;line-height: 57px;height: 56px;" class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button-full mdl-color--green mdl-color-text--white"><i class="material-icons">file_download</i> ดาวน์โหลด</a> </div>'
       +'<div style="text-align: center">ร่วมบอกต่อบริการสร้างวิดีโอพร้อมข้อความ คลิกเลย</div>'
        +'<div style="margin: 20px auto" onclick="fbshareCurrentPage()" class="mdl-cell mdl-cell--6-col mdl-cell--4-col-tablet mdl-cell--6-col-phone"> <button class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button-full mdl-color-text--white btn-facebook"><i><img src="svg/facebook.svg"></i> แชร์ด้วยFacebook</button> </div>'


        +'<div style="text-align: center; cursor: pointer" onclick="location.reload();">ถ้าต้องการสร้างวิดีโออื่นๆ กรุณารีเฟรชหน้านี้ หรือ <span ><i class="material-icons v_align_mid">replay</i> คลิกที่นี่</span></div>'

        //body : modalCaptureing()

    };

    imodal = new Modal(config);







    imodal.open()



    console.info('size :: ', size)
}



function downloadVideo(e){

    // e.preventDefault()
    // ga('Main.send', 'event', 'สร้างรูปถวายความอาลัย Template 6', 'Download', username.value);
    e.href = videoOutputURL;
    e.download = videoOutputURL;

    ga('send', 'event', {
        eventCategory: campaignName,
        eventAction: 'click',
        eventLabel: "BTN Download"
    });

}


/*
function postVideoToFacebook() {

    FB.login(function (response) {

        //postImageToFacebook(response.authResponse.accessToken, blob, handler);


        console.log(response.authResponse.accessToken)

        videoOutputURL ="http://27.254.156.24:8082/frameencoder/downloads/untitled-574.mp4"


        makeApiRequest(
            response.authResponse.accessToken,
            {
                url: 'me/videos',
                data: {file_url:videoOutputURL, description: 'title'},
                method: 'POST'
            }, successCb, errorCb);



    }, {scope: "publish_actions"});



}

function successCb() {

}

function errorCb() {

}



 function makeApiRequest(accessToken, config, successCallback, errorCallback) {
    var baseUrl = 'https://graph.facebook.com/v2.10/';

    // parse config and defaults
    var config = config || {},
        url = config.url || 'me',
        data = config.data || {},
        method = config.method || 'GET';

    config.url = baseUrl + url + '&access_token=' + accessToken;

    // make the api request
    $.ajax(config)
        .done(function(data) {
                if (!!successCallback) {
                    successCallback(data);
                } else {
                    console.log(data);
                }
            }
        ).error(function(xhr) {
        errorCallback(xhr);
    });
}
*/




/*if( navigator.userAgent.indexOf('Chrome')  > -1 ){


   // alert('this is chrome')
    // Do something in Chrome
}*/









var App = React.createClass({

    getInitialState: function() {
        return {value: videos[videoId].text.y,value2:videos[videoId].text.fontSize};
    },

/*    componentDidMount: function() {
        //this.setState({seconds: this.state.seconds + 1});

        console.log('tick')
    },*/

    handleChange: function (e) {
        //const title = e.target.value;
        //str = "ข้าพระพุทธเจ้า " + title;
        str =  e.target.value;
        txt.text = str;
        //txt.alpha = 1;
        stage.update();
        // console.log(title)
    },
    handleRangeChange: function (e) {
        this.setState({value: e.target.value});
        //txt.font = e.target.value + "px "+ txt.fontFaceName;
        txt.y = e.target.value;
        /*txt.scaleX = e.target.value ;
        txt.scaleY = e.target.value ;*/
        //console.log(e.target.value)
        stage.update();
    },

    handleRangeChange2: function (e) {
        this.setState({value2: e.target.value});
        //txt.font = e.target.value + "px psl_malineeitalic";
        txt.font = e.target.value + "px "+ txt.fontFaceName;
        //console.log(e.target.value)
        stage.update();
    },

    render: function () {
        return (

            <fieldset className="uk-fieldset">

                <div className="mdl-textfield mdl-js-textfield mdl-textfield--floating-label mdl-textfield-full">
                    <input className="mdl-textfield__input" type="text" placeholder="ชื่อของคุณ..." id="name" onChange={this.handleChange}/>
                        {/*<label className="mdl-textfield__label" for="name">ชื่อของคุณ...</label>*/}
                </div>

                {/*<div className="pad24-0">
                    <label for="offset" className="pad0-16">ปรับตำแหน่ง</label>
                    <input onChange={this.handleRangeChange}  value={this.state.value} className="mdl-slider mdl-js-slider" type="range" id="offset" min="0" max="360" step="1" />
                </div>*/}


                <div className="pad24-0">
                    <label for="offset" className="pad0-16">ปรับขนาดตัวอักษร</label>
                    <input onChange={this.handleRangeChange2}  value={this.state.value2} className="mdl-slider mdl-js-slider" type="range" id="offset" min="1" max="60" step="1" />
                </div>

            </fieldset>

        );
    }
});


React.render(<App />, document.getElementById('app'));
