import documentReady from '@assets/js/documentReady';
import axiosApi from '@assets/js/axios-api';
import param from '@assets/js/param';

documentReady(async () => {

  const input = document.querySelector('input[type="file"]');
  const imgPic = document.querySelector('.img-pic');
  const userIcon = document.querySelector('.user-icon');
  const imgProfile = document.querySelector('.img-profile');
  const section = document.querySelectorAll('.mini-card');
  
  section.forEach(item => {
    if (window.location.href.includes(item.getAttribute('data'))) item.classList.add('sectionSelect')
    if (window.location.href.includes('account/home') && item.getAttribute('data') == 'account/account') item.classList.add('sectionSelect');
  });

  input.addEventListener('change', () => {
    const file = input.files[0];
    const reader = new FileReader();

    reader.addEventListener('load', () => {
      const base64String = btoa(reader.result);
      const imgBase64 = `data:${file.type};base64,${base64String}`;
      const getImgProfile = imgProfile?.getAttribute('src');

      var img = new Image();
      img.src = imgBase64;

      img.onload = function() {
        var newWidth = 250;
        var newHeight = 250;
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        canvas.width = newWidth;
        canvas.height = newHeight;
        ctx.drawImage(img, 0, 0, newWidth, newHeight);
        var newBase64String = canvas.toDataURL('image/jpeg');

        if(getImgProfile) {
          imgProfile.setAttribute("src",newBase64String);
        }
        else{
          userIcon.style.display = 'none';
          imgPic.style.display = 'flex';
          imgPic.setAttribute("src",newBase64String);
        }

        const { data } = axiosApi.post(
          'index.php?route=account/account/setImageCustomer',
          param({
            imgCostumer: newBase64String,
          })
        );
      }
    });
    if(file) reader.readAsBinaryString(file);
  });
});