
/**
 *
 * @authors Eric Hsiao
 *
 */

storePage = function (_couponData) {

  //private menbers 
  var couponData = [];
  var popoutClickHandle = function () { };

  //private methods
  function init() {
    console.log('storePage is init.');

    //////////////////////////////////////////
    //UI

    $('.video__close').click(function (e) {
      e.preventDefault();
      TweenMax.to('.video__popout', 0.3, { autoAlpha: 0 });
      player.stopVideo();
    });

    $('.game__popout__close').click(function (e) {
      e.preventDefault();
      TweenMax.to('.game__popout', 0.3, { autoAlpha: 0 });
    });

    $('.game__popout__submit').click(function (e) {
      e.preventDefault();
      popoutClickHandle();
    });
  }

  function updateCoupon(_data) {
    couponData = _data;
    console.log('============== updateCoupon ==============');
    // console.log(userInfo.goodinfo);

    for (let index = 0; index < couponData.length; index++) {
      var _coupon;
      if (couponData[index].lp < 5) {
        _coupon = new couponItem(index, couponData[index]);
      } else {
        var _isLock = true;

        if ($.cookie('luckydraw.isVideoUnlock') === 'true') {
          _isLock = false;
        } else {
          _isLock = true;
        }

        console.log('luckydraw.isVideoUnlock = ' + $.cookie('luckydraw.isVideoUnlock') + ', _isLock = ' + _isLock);

        //YOUTUBE LINK
        _coupon = new couponItem(index, $.extend(couponData[index], { lock: _isLock, video: YOUTUBE__ID }));
      }
    }
  }

  function showPopout(_html) {
    $('.game__popout').show();
    TweenMax.set('.game__popout', { autoAlpha: 0 });

    $('.game__popout__content .content').hide();
    $('.game__popout__submit').hide();
    $('.game__popout__content .content__result').show();
    $('.game__popout__content .content__result__text').html(_html);
    TweenMax.to('.game__popout', 0.5, { autoAlpha: 1 });
  }

  function useCoupon(_id, _number, _callback) {

    //按下submit才執行
    popoutClickHandle = function () {
      $.ajax({
        type: "POST",
        url: API__DOMAIN + "api2021/redeem/" + LINE__ID + '/' + _id,
        data: {
          name: USER__NAME
        },
        dataType: "json",
        success: function (response) {
          console.log('================== response ===================');
          console.log(response);
          if (response.succ) {
            //顯示成功與否

            showPopout('<p>兌換完成<br>請至LINE錢包<br>查看點數</p>');

            //Coupon更新自己狀態
            _callback();

            //Coupon更新玩家狀態、剩餘點數
            // updateUserData();

            TweenMax.to('.game__popout', 0.3, { autoAlpha: 0 });

          } else {
            //錯誤訊訊息
            showError("兌換錯誤：<br>" + response.err);
          }

        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          console.log("Status: " + textStatus + ", Error: " + errorThrown);
          // alert('很抱歉，資料讀取錯誤 請稍後再試。');
          showError("連線錯誤：<br>" + "Status: " + textStatus + ", Error: " + errorThrown);
        }
      });
    };
  }

  //////////////////////////////////////

  function intoPage() {

  }

  function leavePage() {

  }

  //constructor
  {
    $(document).ready(function () {
      init();
    });
  }

  //public

  return {
    intoPage: function () {
      intoPage();
    },
    leavePage: function () {
      leavePage();
    },

    updateCoupon: function (_data) {
      updateCoupon(_data);
    },

    showPopout: function (_html) {
      showPopout(_html);
    },

    useCoupon: function (_id, _number, _callback) {
      useCoupon(_id, _number, _callback);
    },
  };
};

var storePage = new storePage();

///////////////////////////////////////////////

var videoCallback;

// Load the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// Replace the 'ytplayer' element with an <iframe> and
// YouTube player after the API code downloads.
var player;
function onYouTubePlayerAPIReady() {
  console.log('Yiutube API Ready');

  player = new YT.Player('video__content', {
    height: '360',
    width: '640',
    videoId: '',
    playerVars: { 'autoplay': 0, 'controls': 0 },
    events: {
      'onStateChange': onPlayerStateChange
    }
  });
}

function onPlayerStateChange(e) {
  console.log('onPlayerStateChange');
  if (e.data == 0) {
    videoCallback();
  }
}