import _Image from './_Image.js';
import _Item from './_Item.js';
import _DB from './_DB.js';
import _FullscreenImage from './_FullscreenImage.js';
import isObject from './util/isObject.js';

function ItemImageController(ivnode){
return { view: function(vnode){
  var item = vnode.attrs.item;
  if(item === null){
    return m('.msg', 'No item chosen.');
    }
  if(typeof item.image_ids === 'undefined'){ item.image_ids=[]; }
  var images = item.image_ids.map(function(image_id){
    if(isObject(image_id)){
      return image_id;
      }
    else{
      return _DB.getRecord(image_id);
      }
    }); 
  var no_images = (images.length === 0);
  return m('.item-image-controller.bg-secondary.text-center', {
        style: 'height: 500px;',
        ondragover: function(e){
          e.preventDefault();
          },
        ondrop: function(e){
          e.preventDefault();  // don't open the file in the browser
          var files = [];
          
          // some browsers use `.items` and some use `.files`, so check for both:
          if (e.dataTransfer.items) {
            for (var i = 0; i < e.dataTransfer.items.length; i++) {
              if (e.dataTransfer.items[i].kind === 'file') {  // If dropped items aren't files, reject them
                files.push( e.dataTransfer.items[i].getAsFile() );
                }
              }
            }
          else {
            for (var i = 0; i < e.dataTransfer.files.length; i++) {
              files.push( e.dataTransfer.files[i] );
              }
            }
          for(var i=0; i<files.length; i++){
            _Image.newFromFile(files[i]).then(function(image){
              _Item.addImage(item, image).then(m.redraw);
              });
            }
          m.redraw();
          }
        }, [
    m('.container.image-list', [
      m('.columns',
                no_images ? [m('.column.col-12', [m('h3', 'Drop Images Here')] )] : images.map(function(image){
                  return m('.column.col-4', [
                    m('.card.c-hand', {onclick: function(){ _LargeImage.src = (image.thumbnail_original_id ? '/thumbnailsdb/'+image.thumbnail_original_id+'.png' : image.src_base64); }},[
                      m('figure', [
                        m('img.img-responsive', {src: (image.thumbnail_180_id ? _Image.thumbnailPath(image, '180') : image.src_base64) }),
                        m('figcaption', image.original_filename)
                        ]),
                      m('button.btn.btn-clear.delete', {onclick: function(e){
                        e.stopPropagation();
                        _Item.deleteImage(item, image);
                        }},'Delete'),
                      (image.is_uploading ? m('progress.progress',{value: image.progress, max: 1.0}) : null)
                      ])
                    ]);
                  })
        )
      ])
    ]);
}}}

export default ItemImageController;