const btnLoginPage = document.querySelector('.btn-login');
const btnUserProfile = document.querySelector('.btn-userProfile');
const btnLogout = document.querySelector('.btn-logout');

let lan = localStorage.getItem('lan');
let defaultLength = 5;
let historyData;

function getCookie(name) {
    const value = `; ${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    if (parts.length === 2) return parts.pop().split(';').shift();
}

let userBasics = JSON.parse(localStorage.getItem('user_profile')) || [];
let inviteCode;

function checkLocal() {
  if(userBasics.length == 0){ return };
  //userBasics = JSON.parse(userBasics);
  if(userBasics !== [] && typeof(userBasics) !== 'string') {
    console.log(typeof(userBasics));
    $('.userName').html(`<h2 class="user-name text-white mt-4 fw-bold">Hi ${userBasics.user_info.userName}</h2>`);
  }
}

$('.dropdown-toggle').click(() => {
  lan = localStorage.getItem('lan');
  checkLan();
});

checkLocal();

function checkLan() {
  if(lan == 'en') {
    $('.btn-makev').css('display', 'none');
    $('.btn-makelong').css('display', 'none');
  } else {
    $('.btn-makev').css('display', 'block');
    $('.btn-makelong').css('display', 'block');
  }
}

checkLan();


function renderView() {
    let token = getCookie('jwt_token');
    if(!token) {
        window.location.replace("login.html");
    }
    // JsLoadingOverlay.show({
    //   "overlayBackgroundColor": "#666666",
    //   "overlayOpacity": 0.9,
    //   "spinnerIcon": "ball-circus",
    //   "spinnerColor": "#000",
    //   "spinnerSize": "3x",
    //   "overlayIDName": "overlay",
    //   "spinnerIDName": "spinner",
    //   "offsetX": 0,
    //   "offsetY": 0,
    //   "containerID": null,
    //   "lockScroll": false,
    //   "overlayZIndex": 99,
    //   "spinnerZIndex": 100
    // });
    axios({
        method: 'post',
        url: 'https://www.choozmo.com:8887/user_profile',
        headers: { 
            'accept': 'text/html',
            'Authorization': `Bearer ${token}`
         }
    }).then(res => {
        console.log(res.data);
        let userInfo = res.data;
        // if(!userInfo.user_info) {
        //    window.location.replace("login.html");
        // }
        localStorage.setItem('user_profile', JSON.stringify(res.data));
          if(userInfo.user_info.left_sec < 20){
            let title = "剩餘秒數不足";
            let text = '您的影片額度即將不足,加值以持續使用';
            let confirmButtonText = '加值';
                    if (lan == 'en') { 
                        title = "Insufficient seconds left!";
                        text = 'Your seconds left is less than 20 seconds, refill to continue making videos.';
                        confirmButtonText = 'Refill';
                    }
            Swal.fire({
                title,
                text,
                icon: 'warning',
                showCancelButton: true,
                cancelButtonText: 'Cancel',
                confirmButtonColor: '#3085d6',
                confirmButtonText
            }).then(result => {
              if (result.isConfirmed) {
                window.open('pricing.html');
              }
            });
          }
        $('.share-fb').attr('href', `https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fvideo.choozmo.com/invite.html?code=${userInfo.user_info.invite_code}`);
        $('.share-twitter').attr('href',
        `https://twitter.com/intent/tweet?text=I%20just%20created%20a%20video%20in%205%20minutes.%20Check%20it%20out%20%F0%9F%91%89%20https%3A%2F%2Fvideo.choozmo.com/invite.html?code=${userInfo.user_info.invite_code}&related=ai_cmm`)
        
        inviteCode = userInfo.user_info.invite_code;
        invitelink=`https://video.choozmo.com/invite.html?code=${userInfo.user_info.invite_code}`
        $('.invite-link').val(invitelink)
        const str = `<img src="static/img/undraw_male_avatar_323b.svg" alt="">
        <p class="card-profile-txt">User Profile</p>
        <p class="card-profile-cnt">${userInfo.user_info.userName}</p>
        <p class="card-profile-cnt">${userInfo.user_info.email}</p>
        <div class="d-flex justify-content-around">
            <div>
                <p set-lan="html:used">已使用</p>
                <p><strong>${userInfo.user_info.total_sec}</strong><span set-lan="html:sec">秒</span></p>
            </div>
            <div>
                <p set-lan="html:left">未使用</p>
                <p><strong>${userInfo.user_info.left_sec}</strong><span set-lan="html:sec">秒</span></p>
            </div>
        </div>`;
        let totalSec = (userInfo.user_info.total_sec == "None") ? 0 : userInfo.user_info.total_sec;
        let leftSec = (userInfo.user_info.left_sec == null)? 0 : userInfo.user_info.left_sec;
        // 使用者名稱
        let userName = `<h2 class="user-name text-white mt-lg-3 mt-xl-1 fw-bold">Hi ${userInfo.user_info.userName}</h2>`;
        // 已使用
        let usedtime=`<h1 class="text-center">${totalSec}&ensp;<span style="font-size:15px;" set-lan="html:sec">秒</span></h1>`;
        if(lang == 'en') {
          usedtime=`<h1 class="text-center">${totalSec}&ensp;<span style="font-size:15px;" set-lan="html:sec">Sec</span></h1>`;
        }
        // 未使用
        let NotUsedTime=`<h1  class="text-center">${leftSec}&ensp;<span style="font-size:15px;" set-lan="html:sec">秒</span></h1>`;
        if(lang == 'en') {
          NotUsedTime=`<h1  class="text-center">${leftSec}&ensp;<span style="font-size:15px;" set-lan="html:sec">Sec</span></h1>`;
        }
        // user資訊
        let infContent=`
        <div class="inf-content">
            <p>${userInfo.user_info.userName}</p>
            <p>************&nbsp;<a href="./reset_pwd_email.html" set-lan="html:resetPsd">更改密碼</a></p>
            <p>${userInfo.user_info.email}</p>
        </div>`;
        if(lang == 'en') {
          infContent=`
            <div class="inf-content">
                <p>${userInfo.user_info.userName}</p>
                <p>***************&nbsp;<a href="./reset_pwd_email.html" set-lan="html:resetPsd">Reset Password</a></p>
                <p>${userInfo.user_info.email}</p>
            </div>`;
        }
        // 歷史紀錄
        // const historicalrecord 
        historyData = {...userInfo};
        var  historicalrecord='';
        var length = userInfo.video_info.length > defaultLength ? defaultLength : userInfo.video_info.length;
        for (var i = 0; i < length; i++) {
          let formatted = userInfo.video_info[i].time_stamp;
          if (lan == 'zh') {
            const timeStamp = userInfo.video_info[i].time_stamp;
            const year = timeStamp.split(',')[0].split('/')[2];
            const arr = timeStamp.split(',')[0].split('/');
            arr.pop();
            arr.unshift(year);
            const fomatDate = [arr.join('/')];
            formatted = fomatDate.concat(timeStamp.split(',')[1]).join('');
          }
            historicalrecord+='\
            <tr>\
            <td class="px-0">'+formatted+'</td>\
            <td class="px-0">'+userInfo.video_info[i].title+'</td>\
            <td class="px-0 w-25">'+userInfo.video_info[i].duration+'</td>\
          </tr>`\
            ';
         
        }

        $('.historical-content').html(historicalrecord); 
        $('.userinf').html(infContent);
        $('.userName').html(userName);
        $('.used-time').html(usedtime);
        $('.not-used-time').html(NotUsedTime);
        $('.card-profile').html(str);
        $('.card-profile').html(str);

        JsLoadingOverlay.hide();
    }).catch(err => {
        JsLoadingOverlay.hide();
        console.log(err);
        //window.location.replace("login.html");
    })
}

renderView();


function getDraft() {
  JsLoadingOverlay.show({
    "overlayBackgroundColor": "#FFFFFF",
    "overlayOpacity": "1",
    "spinnerIcon": "ball-circus",
    "spinnerColor": "#B9DDF3",
    "spinnerSize": "1x",
    "overlayIDName": "overlay",
    "spinnerIDName": "spinner",
    "offsetX": 0,
    "offsetY": 0,
    "containerID": "draft-table",
    "lockScroll": false,
    "overlayZIndex": 9998,
    "spinnerZIndex": 9999
  });
  let token = getCookie('jwt_token');
  axios({
    method: 'post',
    url: 'https://www.choozmo.com:8887/draft_list',
    headers: { 
        'accept': 'application/json',
        'Authorization': `Bearer ${token}`
     }
  }).then(res => {
    console.log(res.data);
    let result = [...res.data];
    let str = '';
    let draftStr = '';
    if(result.length > 0){
      for(let i = 0;i < result.length; i++) {
        draftStr += `<tr>
                  <td>${result[i].title}</td>
                  <td>
                  <span class="me-md-3 draft-content-icon" id="${result[i].id}" onclick="gotoDraft(${result[i].id})">
                    <i class="fas fa-edit"></i>
                    </span>
                    <span class="ms-md-3 draft-content-icon draft-content-delete" id="${result[i].id}" onclick="deleteDraft(${result[i].id})">
                    <i class="fas fa-trash-alt"></i>
                    </span>
                    </td>
                </tr>`
      }
      let titleTxt = '標題';
      let editTxt = '編輯';
      let nodraftTxt = '目前沒有草稿喔';
      if(lan == 'en') {
        titleTxt = 'Video Title';
        editTxt = 'Edit';
        nodraftTxt = 'no_draft';
      }
      str = `<table class="table text-center">
      <thead>
        <tr>
          <th scope="col" set-lan="html:video_title">${titleTxt}</th>
          <th class="px-0" scope="col" set-lan="html:draft_edit">${editTxt}</th>
        </tr>
      </thead>
      <tbody class="draft-content">${draftStr}</tbody>
      </table>`
      $('.draft-table .card').html(str);
      JsLoadingOverlay.hide();
    } else {
      str = `<div>
              <h5 set-lan="html:no_draft">${nodraftTxt}</h5>
              <img src="static/img/undraw_void_3ggu.svg" width="80">
            </div>`;
      $('.draft-table .card').html(str); 
      JsLoadingOverlay.hide();
    }
  }).catch(err => {
    console.log(err);
  });
}

getDraft();

function checkLogin() {
    let token = getCookie('jwt_token');
    if(token) {
        btnLoginPage.style.display = 'none';
        btnLogout.style.display = 'block';
        btnUserProfile.style.display = 'block';
    } else {
        window.location.href = 'login.html';
        btnLoginPage.style.display = 'block';
        btnLogout.style.display = 'none';
        btnUserProfile.style.display = 'none';
    }
}


checkLogin();
$(".historical-record").hide();

$( ".check-history" ).click(function() {
  $(".historical-record").slideToggle(150);
  $(".arrowdown").toggleClass("arrowdoup");
  });

$('.draft-table').hide();
$('.draft .arrowdown').click(function() {
    $(".draft-table").slideToggle(150);
    $(".draft .arrowdown").toggleClass("arrowdoup");
});

var loaded_data = ''
function openNav() {
  document.getElementById("mySidenav").style.width = "250px";
  document.querySelector('.loader').style.display = "block";
  let token = getCookie('jwt_token');
  axios({
    method: 'post',
    url: 'https://www.choozmo.com:8887/history_input',
    headers: { 
        'accept': 'application/json',
        'Authorization': `Bearer ${token}`
     }
  }).then(res => {
    console.log(res.data);
    loaded_data = res.data;
    var historyList = document.querySelector('.historyList');
    historyList.innerHTML = '';
    for (var obj of loaded_data) {
      var list = document.createElement('li');
      list.id = obj.id;
      // div-imgfr
      var divImgfr = document.createElement('div');
      divImgfr.classList.add('item_imgfr');
      var img = document.createElement('img');
      img.setAttribute('src', obj['image_urls'][0]);
      divImgfr.appendChild(img);
      // div-content
      var contentBox = document.createElement('div');
      contentBox.classList.add('content-box');
      var boxTitle = document.createElement('p');
      boxTitle.classList.add('box-title');
      boxTitle.textContent = obj.name;
      boxTitle.id = obj.id;
      boxTitle.setAttribute('onclick', `direct(${obj.id})`);

      var boxLink = document.createElement('span');
      boxLink.classList.add('box-link');
      boxLink.setAttribute("data-url", obj.link);
      boxLink.setAttribute('onclick', 'view()');
      boxLink.innerHTML = '<i class="fas fa-play-circle me-1"></i>觀看影片';
      contentBox.appendChild(boxTitle);
      contentBox.appendChild(boxLink);
      list.classList.add("historyList-item");
      list.setAttribute('onclick', `direct(${obj.id})`);
      list.appendChild(divImgfr);
      list.appendChild(contentBox);
      historyList.appendChild(list);
    }
    document.querySelector('.loader').style.display = "none";
  
  }).catch(err => {
    console.log(err);
  });
}

function direct(id) {
    location.href = `make_video2.html?id=${id}`;
}

function view() {
    event.stopPropagation();
    console.log(event.target);
    if (event.target.nodeName === 'I') {
      return;
    } else {
      window.open(`http://${event.target.dataset.url}`, '_blank');
    }
  }

function gotoDraft (id) {
  location.href = `make_video2.html?draftid=${id}`;
}
function deleteDraft(id) {
  let token = getCookie('jwt_token');
  JsLoadingOverlay.show({
    "overlayBackgroundColor": "#FFFFFF",
    "overlayOpacity": "1",
    "spinnerIcon": "ball-circus",
    "spinnerColor": "#B9DDF3",
    "spinnerSize": "1x",
    "overlayIDName": "overlay",
    "spinnerIDName": "spinner",
    "offsetX": 0,
    "offsetY": 0,
    "containerID": "draft-table",
    "lockScroll": false,
    "overlayZIndex": 9998,
    "spinnerZIndex": 9999
  });
  axios({
    method: 'post',
    url: 'https://www.choozmo.com:8887/del_draft',
    headers: { 
        'accept': 'application/json',
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
    },
    data: { "id": id }
  }).then(res => {
    console.log(res.data);
    //$('.draft-content-delete').html('<i class="fas fa-trash-alt"></i>');
    JsLoadingOverlay.hide();
    getDraft();
  }).catch(err => {
    console.log(err);
  });
}

$('.share-email').click(function() {
  var link = `mailto:me@example.com?subject=
  ${encodeURIComponent("Check out AI Spokesgirl")}
  &body=${encodeURIComponent(`I just created a video in 5 minutes, check out this amazing video making tool. https://video.choozmo.com/invite.html?code=${inviteCode}`)}`;
    window.location.href = link;
});

function trialStart() {
  let title = "歡迎使用AiSpokesgirl!將你的生活、創作 、宣傳做成影片。";
  let html = `<p>您有  <b> 2 </b>  分鐘影片製作額度。</p><br>
              <p>您可以使用:</p>
              <ul>
                <li>1. 短影片製作</li>
                <li>2. 個人歷史紀錄儲存</li>
                <li>3. 影片下載(Mp4)</li>
              </ul>
              <p>欲使用其他功能請升級為Premium方案</p>`;
  let confirmButtonText = '我知道了!';
  if (lan == 'en') { 
    title = "Welcome to AiSpokesgirl! Make your first video for promotion, creation and life today!";
    html = `<p>You get<b>2</b>minutes of video</p><br>
            <p>Here are several features you can try,</p>
            <ul>
              <li>1. Short video creation</li>
              <li>2. Personal video history</li>
              <li>3. Downloadable format (MP4)</li>
            </ul>
            <p>Want to access more features? Follow the link below to upgrade to a paid plan today.</p>`;
    confirmButtonText = 'OK';
  }
  Swal.fire({
    title,
    html,
    icon: 'success',
    confirmButtonColor: '#3085d6',
    confirmButtonText
  });
}

function trialEnd() {
  let title = "您的試用即將結束!好的idea值得延續,透過影片將你的idea完整呈現。";
  let html = `<p>前往網站以升級為Premium方案,或是聯絡我們以洽詢細節。</p>`;
  let confirmButtonText = '立即升級';
  if (lan == 'en') { 
    title = "Your trial is gonna over soon. Your idea worth spreading.";
    html = `<p>All good things don't have to come to an end.</p><br>
            <h5>Show your idea through video</h5><br>
            <p>Want to access more features? Follow the link below to upgrade 
            to a paid plan today or contact us get further details.</p>`;
    confirmButtonText = 'Upgrade Now';
  }
  Swal.fire({
    title,
    html,
    icon: 'success',
    confirmButtonColor: '#3085d6',
    confirmButtonText
  }).then(result => {
    if (result.isConfirmed) {
      location.href = "pricing.html";
    }
  });;
}


var screenWidth = screen.width;
console.log(screenWidth)


$( ".menu-bar" ).click(function() {
  $(".sidenav").show();
});

$( ".close-btn" ).click(function() {
  $(".sidenav").hide();
});

$("#lang-manu").hide();

$( "#changeLanguage" ).click(function() {
  $("#lang-manu").slideToggle();
  $("#lang-arrow").toggleClass("arrowdoup");
});

function copyEvent(id) {
  var Url = document.getElementById("invite-link");
  Url.select();
  // window.getSelection().selectAllChildren(str);
  document.execCommand("Copy");
  toastr.options = {
    // 參數設定[註1]
    "closeButton": false, // 顯示關閉按鈕
    "debug": false, // 除錯
    "newestOnTop": false,  // 最新一筆顯示在最上面
    "progressBar": false, // 顯示隱藏時間進度條
    "positionClass": "toast-top-center", // 位置的類別
    "preventDuplicates": false, // 隱藏重覆訊息
    "onclick": null, // 當點選提示訊息時,則執行此函式
    "showDuration": "300", // 顯示時間(單位: 毫秒)
    "hideDuration": "1000", // 隱藏時間(單位: 毫秒)
    "timeOut": "1000", // 當超過此設定時間時,則隱藏提示訊息(單位: 毫秒)
    "extendedTimeOut": "1000", // 當使用者觸碰到提示訊息時,離開後超過此設定時間則隱藏提示訊息(單位: 毫秒)
    "showEasing": "swing", // 顯示動畫時間曲線
    "hideEasing": "linear", // 隱藏動畫時間曲線
    "showMethod": "fadeIn", // 顯示動畫效果
    "hideMethod": "fadeOut" // 隱藏動畫效果
  }
  toastr.success("複製成功");
}