class URLUploader {
   constructor(element, opts) {
      this.element = element;
      this.form = $(this.element).find('form').get(0);
      this.uid = [...Array(12)].map(_ => Math.floor(Math.random() * 10)).join("");
      $(this.element).find('.uploadbtn').click(evt => { evt.preventDefault(); this.onStartUploadClicked() });
   }
   async onStartUploadClicked() {
      $(this.element).click(evt => {
         $('.reurlupload form').hide();
      });

      this.startProgressMonitor();
      const res = await fetch(`${this.form.action}&upload_id=${this.uid}`, { method: "POST", body: new FormData(this.form) });
      const ret = await res.json();
		const redirect_params = ret.map(t => "st=" + t.file_status + "&fn=" + t.file_code).join("&");
		document.location = `/upload_result?${redirect_params}`;
   }
   startProgressMonitor() {
      const urls = $(this.form).prop('url_mass').value.match(/[^\r\n]+/g);
      const filenames = urls.map(x => x.match('[^\/]+$')[0]);
      const onabort = async () => {
         const res = await fetch(`${this.form.action}&kill=${this.uid}`);
         const ret = await res.text();
         if(ret == 'OK') document.location.reload();
      };
      this.tracker = new ProgressTracker($(this.element).find('.progress_div'), { "filenames": filenames, "onabort": onabort });
      setInterval(_ => {
        $.ajax({
          url: `${new URL(this.form.action).origin}/tmp/${this.uid}.json`,
          dataType: 'jsonp',
          jsonpCallback: 'update_stat',
          success: evt => this.tracker.update(evt.loaded, evt.total),
        });
      }, 1000);
   }
}
