{% extends "admin/admin-layout.html" %}

{% block app_content %}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/cropper/2.3.4/cropper.min.css'>
<h1>Update Officer Photo</h1>
	<!-- input file -->
	<div class="box">
		<input type="file" id="file-input">
	</div>
	<!-- leftbox -->
	<div class="box-2">
		<div class="result"></div>
	</div>
	<!--rightbox-->
	<div class="box-2 img-result hide">
		<!-- result of crop -->
		<img class="cropped" src="" alt="">
	</div>
	<!-- input file -->
	<div class="box">
		<div class="options hide">
			<label> Width</label>
			<input type="number" class="img-w" value="512" min="512" max="512" />
		</div>
		<!-- save btn -->
		<button class="btn save hide">Save</button>
	</div>
<script src="{{ url_for('static', filename='js/jquery-3.6.3.min.js') }}" charset="utf-8"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/cropperjs/0.8.1/cropper.min.js'></script>
<script charset="utf-8">
    
    // vars
let result = document.querySelector('.result'),
img_result = document.querySelector('.img-result'),
img_w = document.querySelector('.img-w'),
img_h = document.querySelector('.img-h'),
options = document.querySelector('.options'),
save = document.querySelector('.save'),
cropped = document.querySelector('.cropped'),
upload = document.querySelector('#file-input'),
cropper = '';


// on change show image with crop options
upload.addEventListener('change', e => {
  if (e.target.files.length) {
    // start file reader
    const reader = new FileReader();
    reader.onload = e => {
      if (e.target.result) {
        // create new image
        let img = document.createElement('img');
        img.id = 'image';
        img.src = e.target.result;
        // clean result before
        result.innerHTML = '';
        // append new image
        result.appendChild(img);
        // show save btn and options
        save.classList.remove('hide');
//        options.classList.remove('hide');
        // init cropper
        cropper = new Cropper(img, { aspectRatio: 1 });
      }
    };
    reader.readAsDataURL(e.target.files[0]);
  }
});

// save on click
save.addEventListener('click', e => {
  e.preventDefault();
  // get result to data uri
  let imgSrc = cropper.getCroppedCanvas({
    width: img_w.value // input value
  }).toDataURL();
  // remove hide class of img
  cropped.classList.remove('hide');
 // img_result.classList.remove('hide');
  // show image cropped
  cropped.src = imgSrc;
  console.log(imgSrc);
    const uploadReq = new Request("/admin/officer/photo/upload", {
        method: "POST",
        body: imgSrc
    });
    fetch(uploadReq).then(async (res) => {
       console.log(res.status)
       if (res.status === 200) {
       user_id = "{{ current_user.id }}"
        window.location = `/admin/officer/${user_id}`
    }
    });
});
</script>
{% endblock %}
