// +-------------------------------------------------+
// � 2002-2004 PMB Services / www.sigb.net pmb@sigb.net et contributeurs (voir www.sigb.net)
// +-------------------------------------------------+
// $Id: HomePageGalleryView.js,v 1.2 2018/10/23 13:50:16 vtouchard Exp $

define([
	'dojo/_base/declare', 
	'dijit/_WidgetBase', 
	'dojo/topic', 
	'dojo/_base/lang', 
	'dijit/registry',
	'dojo/dom-construct',
	'dojo/dom-attr',
	'dojo/dom-style',
	'dojo/dom',
	'dojo/store/Memory',
	'dojo/data/ItemFileReadStore',
	'dojo/store/DataStore',
	'dojo/store/Observable',
	'dojo/on'], function(declare, widget, topic, lang, registry, domConstruct, domAttr, domStyle, dom, Memory, ItemFileReadStore, DataStore, Observable, on) {
    return declare([widget], {
    	displayedPics: 10,
    	firstInit: true,
    	currentlyDisplayedBorrowers: null,
    	galleryNode: null,
    	paginatorLeft: null,
    	paginatorRight: null,
    	currentPage: 0,
        buildRendering : function() {
        },
        postCreate : function() {
        	this.createGallery();
        	
        	var borrowersCallback = dojoConfig.bibloto.jsonRpcServer.pmbesEmpr_bibloto_empr_list([]);
            borrowersCallback.addCallback(lang.hitch(this, function(data){
            	this.borrowers = new Memory({data: data.data});
//            	console.log(this.borrowers);
    		}));
        	this.show();
        	this.currentlyDisplayedBorrowers = [];
        	this.createMessageDiv(dojoConfig.bibloto.appParams.msg_search_title);
        	this.createPaginator('left');
        	this.createPaginator('right');
        	this.displayPaginator('none', 'right');
        	this.displayPaginator('none', 'left');
        	this.own(topic.subscribe('HomePageGalleryKeyboard', lang.hitch(this, this.handleEvents)));        	
        },
        handleEvents: function(evtType, evtArgs){
        	switch(evtType){
        		case 'letterRemoved':
        		case 'letterClicked':
        			this.currentPage = 0;
        			this.displayBorrowers(this.getBorrowers(evtArgs));
        			break;
        		case 'fullKeyboard':
        			this.hide();
        			break;
        	}
        },
        createGallery: function(){
        	this.galleryNode = domConstruct.create('div', {
        		'class': 'gallery-node',
        	}, this.domNode);
        },
        show: function(){
        	domStyle.set(this.domNode, 'display', 'block');
        },
        hide: function(){
        	domStyle.set(this.domNode, 'display', 'none');
        },
        displayBorrowers: function(borrowers){
        	this.removePics();
        	this.show();
        	if(borrowers.length){
            	var ulContainer = domConstruct.create('ul', {'class': 'uk-grid'}, this.galleryNode)
	        	this.currentlyDisplayedBorrowers.push(ulContainer);
            	for(var i=0 ; i<borrowers.length  ; i++){
	        		var li = domConstruct.create('li', {
	        			'class':'uk-width-1-5',
	        		}, ulContainer);
	        		var divContainer = domConstruct.create('div', {
	        			'class': 'structure-container'
	        		}, li);
	        		var divImageContainer = domConstruct.create('div', {
	        			'class': 'image-container'
	        		}, divContainer);
	        		
	        		
	        		var imgURL = dojoConfig.bibloto.appParams.thumbnail_url.
            			replace('!!empr_id!!', borrowers[i].empr_id).
            			replace('!!empr_cb!!', borrowers[i].empr_cb);
	        		if(!this.checkImage(imgURL)){
	        			imgURL = dojoConfig.bibloto.appParams.thumbnail_url.
            			replace('!!empr_id!!', 'no_image').
            			replace('!!empr_cb!!', 'no_image')
	        		}
	            	var img = domConstruct.create('img', {
	            		'data-borrower-code': borrowers[i].empr_cb,
	            		style: {
	            			border: '1px solid black',
	            		},
	            		src: imgURL,
	            		'class': 'borrower-pic',
	            	}, divImageContainer);
	            	var divNameContainer = domConstruct.create('div', {
	        			'class': 'name-container'
	        		}, divContainer);
	            	var divName = domConstruct.create('p', {
	            		innerHTML: borrowers[i].empr_prenom+' '+borrowers[i].empr_nom
	        		}, divNameContainer);
	            	
	            	this.currentlyDisplayedBorrowers.push(li);
	            	on(img, 'click', lang.hitch(this, this.imgClicked, borrowers[i].empr_cb));
	        	}
        	}else{
        		this.displayPaginator('none', 'right');
           	 	this.displayPaginator('none', 'left');
        		this.createMessageDiv(dojoConfig.bibloto.appParams.msg_no_user_found);
        	}
        },
        getBorrowers: function(data){
        	var start = start || 0;
        	var search = data.search.replace('&nbsp;', '');
        	this.currentResult = [];
        	if(search != ''){
	        	search = search.toLowerCase();
	        	search = search.charAt(0).toUpperCase() + search.slice(1)
	        	var searchExp = "^"+search;
	        	var regEx = new RegExp(searchExp, 'i');
	        	var result = this.borrowers.query({empr_nom: regEx});
	        	if(result.length){
	        		if(result.length > this.displayedPics){ //Il y'a plus de 8 résultats
	        			this.displayPaginator('block', 'right');
	        			if(this.currentPage > 1){
	        				this.displayPaginator('block', 'left');
	        			}
	        		}
	        		if(this.currentPage > 0){
	        			this.displayPaginator('block', 'left');
	        		}
	        		if(this.currentPage == 0){
	        			this.displayPaginator('none', 'left');
	        		}
	        		var start = this.currentPage*this.displayedPics;
	        		var borrowersFound = result.slice(start, start+this.displayedPics);
	        		if(borrowersFound.length < this.displayedPics){
	        			this.displayPaginator('none', 'right');
	        		}
	        		return result.slice(start, start+this.displayedPics);	
	        	}
        	}else{
        		this.hide();
        	}
        	return [];
        },
        removePics: function(){
        	this.currentlyDisplayedBorrowers.forEach(function(pic){
        		domConstruct.destroy(pic);
        	});
        },
        imgClicked: function(emprCb){
        	 this.displayPaginator('none', 'right');
        	 this.displayPaginator('none', 'left');
        	 topic.publish('buffer', 'eltAdded', {
                elt : emprCb
        	 });
        },
        clear: function(){
        	this.removePics();
        	this.hide();
        	this.createMessageDiv(dojoConfig.bibloto.appParams.msg_search_title);
        },
        createMessageDiv: function(message){
        	var div = domConstruct.create('div', {class:'gallery-user-message', innerHTML: message}, this.domNode)
        	this.currentlyDisplayedBorrowers.push(div);
        },
        checkImage: function(imgURL){
        	 var http = new XMLHttpRequest();
        	 http.open('HEAD', imgURL, false);
        	 http.send();
        	 return http.status != 404;
        },
        createPaginator: function(direction){
        	this['paginator'+direction] = domConstruct.create('div', {
        		'class': 'paginator-'+direction,
        		style:{
        			float: direction
        		},
        		innerHTML: '<p><i class="fa fa-arrow-'+direction+'" aria-hidden="'+direction+'"></i></p>',
        	}, this.domNode);
        	on(this['paginator'+direction], 'click', lang.hitch(this, this.paginatorClicked, direction));
        },
        displayPaginator: function(display, direction){
        	domStyle.set(this['paginator'+direction], 'display', display);
        },
        paginatorClicked: function(direction){
        	if(direction == 'right'){
        		this.currentPage++ ;
        	}else{
        		this.currentPage--;
        	}
        	this.displayBorrowers(this.getBorrowers({search: dom.byId('keyboard-field').innerHTML}));
        }
    });
});
