var fileManager = {
	selected: [], // stocke les fichiers déjà enregistrés
	currentSelected: [], // stocke les fichiers en cours
	toRemove: [],
	callback: null, // indique la fonction à exécuter pour le renvoi des fichiers sélectionnées à la validation de la sélection
	subFolder: '0', // indique le sous-répertoire dans lequel les fichiers seront uploadés
	forSubcontract: false, // indique si on upload des fichiers pour les contrats ou sous-contrats
	js_confirm: null, // la jquery confirm
	parent: null,

	init: function(title, chosen, category, callback, forSubcontract, parent, novation) {
		this.selected = ( typeof(chosen) != 'undefined' ) ? chosen : [];
		this.currentSelected = [];
		this.callback = ( typeof(callback) != 'undefined' ) ? callback : null;
		this.forSubcontract = ( typeof(forSubcontract) != 'undefined' ) ? forSubcontract : null;
		this.category = category; // stocke le sous-répertoire d'upload
		this.subFolder = category; // stocke le sous-répertoire d'upload
		this.parent = parent;
		this.novation = ( typeof(novation) != 'undefined' ) ? true : false;
		this.js_confirm = this.renderModal(title);
	},
	initAddFile: function() {
		var that = this;
		$('#add_files').off('click').on('click', function() {
			var index = objectLength(that.currentSelected);
			console.log('add_files');
			console.log(index);
			if (index > 1) {
				var isValid = that.checkValidity(index - 1);
			} else {
				var isValid = true;
			}

			if (isValid) {
				var infos = {
					pdfFile: {},
					docFile: {},
					title: '',
					effective_date: '',
				};
				that.newFile(infos);
				that.updateImportedFilesMessage(objectLength(that.currentSelected));
			}
		});
	},
	checkValidity: function(index) {
		// console.log('checkValidity');
		// console.log(index);

		var selector = '#uploader_files_' + index + ' form';
		// console.log(selector);
		var form = $(selector);
		// console.log(form);
		var fields = selector + ' input,' + selector + ' textarea,' + selector + ' select';
		// console.log(selector);
		var validity = true;

		var pdfFile = this.currentSelected[index].pdfFile;
		// console.log(typeof(pdfFile));

		if (typeof(pdfFile.name) == 'undefined') {
			console.log("Pas de fichier");
			$(selector + '[name="import_pdf_form"] .contract-file-upload').addClass('error');
			validity = false;
		} else {
			$(selector + '[name="import_pdf_form"] .contract-file-upload').removeClass('error');
		}

		$(fields).filter('[required]').each(function(i, required){
			// console.log(required);
			if ($(required).val() == '') {
				if ($(required).hasClass('chosen-select')) {
					$(required).siblings('.chosen-container').addClass('form-control error pt-0');
				} else {
					$(required).addClass('error');
				}
				// console.log('validity false');
				// console.log(required);
				validity = false;
			} else {
				if ($(required).hasClass('chosen-select')) {
					$(required).siblings('.chosen-container').removeClass('form-control error pt-0');
				} else {
					$(required).removeClass('error');	
				}
			}
		});
		return validity;

	},
	initDeleteRow: function(selector) {
		var that = this;
		$(selector + ' button.contract-del-btn').off('click').on('click', function() {
			var index = $(this).data('index');
			// TODO effacer currenselect[index] et mettre dans elements à deleter
			that.removeRow(index);
			that.updateImportedFilesMessage(objectLength(currentSelected));
		});
	},
	initDeleteFile: function(selector, selector2) {
		// console.log(this, selector, selector2);
		var that = this;
		$(selector2 + ' .imported_files ul.jFiler-items-list li a.file-del-btn').off('click').on('click', function() {
			that.removeFile(this, selector, selector2);
		});
	},
	renderModal: function(title) {
		var that = this;
		var confirm = $.confirm({
			title: title,
			columnClass: 'col-md-9',
			content: function() {
				var content = '\
					<div class="row">\
						<div class="col-12" id="files_selection"></div>\
						<div class="col-12 text-center text-white mb-2" id="no_imported_files">'+translate.getText.no_imported_files+'</div>\
						<div class="col-12 text-center mb-0"><button class="btn btn-xs btn-success uppercase weight-700" id="add_files"><i class="glyph-icon icon-plus"></i> '+translate.getText.new_file+'</button></div>\
					</div>\
				';
				return content;
			},
			onContentReady: function() {
				if ( objectLength(that.selected) > 0 ) {
					$.each(that.selected, function(i, elem) {
						that.newFile(that.selected[i]);
					});
				}
				that.initAddFile();
				that.updateImportedFilesMessage(objectLength(that.currentSelected));

			},
			type: 'orange',
			theme: 'theme2',
			typeAnimated: true,
			buttons: {
				validate: {
					text: '<i class="glyph-icon icon-elusive-ok"></i>' + translate.getText.validate,
					btnClass: 'btn-green',
					action: function() {
						var isValid = true;
						$.each(that.currentSelected, function(i, elem) {
							var selector = '#uploader_files_' + i;
							isValid = isValid && that.checkValidity(i);
							// vérifie qu'il y ait bien un fichier PDF d'uploadé
							/*
							$(selector + ' .contract-file-upload').removeClass('error');
							if ( typeof(that.currentSelected[i].pdfFile.name) === 'undefined' ) {
								$(selector + ' .contract-file-upload').addClass('error');
							}
							*/
						});

						if (!isValid) {
							return false;
						} else {
							// retourne les fichiers sélectionnés en appelant la fonction de retour des paramètres
							that.returnSelection();
						}
					}
				},
				close: {
					text: '<i class="glyph-icon icon-elusive-cancel"></i>'+translate.getText.cancel,
					btnClass: 'btn-red',
					action: function() { }
				}
			}
		});
		return confirm;
	},
	renderUploader: function(index, file, selector, uploadRoute, extensions, chooseText) {
		console.log("renderUploader");
		console.log(selector);
		var that = this;
		console.log(that);
		renderUploaderFiler(index, file, selector, uploadRoute, extensions, chooseText, that);
	},
	newFile: function(file) {
		console.log('newFile');
		console.log(file);
		// empile les contrats sélectionnés
		this.currentSelected.push(file);
		// charge le contrat sélectionné
		this.newUploader(file);
		initChosen();
		initValidator();
	},
	newUploader: function(file) {
		console.log('new uploader');
		console.log(file);
		var that = this;
		console.log(that.novation);
		// var index = getIndexOf(this.currentSelected, file.id);
		var count = objectLength(this.currentSelected);
		var index = count - 1;
		var path = '/assets/apps/ContractDrive/templates/';
		if (that.novation) {
			var third_parties = null;
			 $.ajax({
				async: false,
				method: "POST",
				dataType: "json",
				url: laroute.route("Stack.API.ThirdParty.getThirdParties"),
				data: { third_party_type: 'counterpart' }
			}).done(function(response) {
				third_parties = response.listing;
			});
		} else {
			var third_parties = null;
		}
		// console.log(third_parties);
		var extra = ((that.category == 3) && (count == 1)) ? false : true;
		var data = {
			index: index,
			count: count,
			id: (typeof(file.id) !== 'undefined') ? file.id : null,
			translate: translate,
			novation: that.novation,
			extra: extra,
			category: that.category,
			third_parties: third_parties
		};
		var content = getTemplate(path + 'files-uploader.html', data);

		$('#files_selection').append(content);
		var selector = '#uploader_files_' + index;
		
		this.initDeleteRow(selector);

		// initialise les file uploader
		this.parent.initFilesUploader(file, index);
		this.renderFiles(file, selector);

		// désaffiche le titre et la date de signature pour le 1er fichier de catégorie "contrat" à upload
		if ( that.subFolder == '3' && index == 0 && !(that.forSubcontract) ) {
			$(selector + ' form[name="import_file_infos_form"]').hide();
		}

		var picker = getDaterangePicker(selector + ' form[name="import_file_infos_form"] input[name="import_file_infos_date"]');
		
		$(selector + ' form[name="import_file_infos_form"] input[name="import_file_infos_date"]').next('span.add-on').off('click').on('click', function() {
			$(selector + ' form[name="import_file_infos_form"] input[name="import_file_infos_date"]').trigger('click');
		});
		
		// sur changement de date
		/*
		$(selector + ' form[name="import_file_infos_form"] input[name="import_file_infos_date"]').on('apply.daterangepicker', function(ev, picker) {
			$(selector + ' form[name="import_file_infos_form"] input[name="import_file_infos_effective_date"]').val(picker.startDate.format(dateRangePickerLanguage.format));
		});
		*/		
	},
	createFile: function(item, index, file) {
		//console.log(that.currentSelected);
		if (file.extension == 'pdf') {
			this.currentSelected[index].pdfFile = file;
			this.currentSelected[index].pdfFile.isNew = true;
		} else {
			this.currentSelected[index].docFile = file;
			this.currentSelected[index].docFile.isNew = true;
		}
		// enregistre le fichier dans les fichiers uploadés en cours
		$(item).find('.jFiler-item-others').html('\
						<span><i class="glyph-icon icon-file"></i> <b>'+translate.getText.type+':</b> '+strtoupper(file.extension)+'</span>\
						<div class="current-status text-success"><i class="icon-jfi-check-circle"></i></div>\
			');
		$(item).find('.jFiler-item-icon i').removeClass('icon-jfi-file-o').removeClass('jfi-file-ext-docx').addClass('icon-file-uploaded '+strtolower(file.extension));
		this.addFileInfo(index);
	},
	addFileInfo: function(index) {
		console.log('addFileInfo');
		console.log(index);
		if (typeof(index) != 'undefined') {
			var selector = '#uploader_files_' + index;
			this.currentSelected[index].title = $(selector + ' form[name="import_file_infos_form"] input[name="import_file_infos_title"]').val();
			var effective_date = $(selector + ' form[name="import_file_infos_form"] input[name="import_file_infos_date"]').val();
			console.log('effective_date');
			console.log(effective_date);
			this.currentSelected[index].effective_date = effective_date;
			var third_party_id = $(selector + ' form[name="import_file_infos_form"] select[name="third_party_out"]').val();
			if (typeof(third_party_id) != 'undefined') {
				this.currentSelected[index].novation = {};
				this.currentSelected[index].novation.third_party_id = third_party_id;
				this.currentSelected[index].novation.name = $(selector + ' form[name="import_file_infos_form"] select[name="third_party_out"] option:selected').text();
			}
			console.log(this.currentSelected[index]);
		}
	},
	removeRow: function(index) {
		console.log('remove row');
		console.log(index);
		$('#uploader_files_' + index).remove();
		this.toRemove.push(this.currentSelected[index]);
		this.currentSelected.splice(index, 1);
		console.log(this.currentSelected);
		console.log(this.toRemove);
		this.reIndex();
	},
	removeFile: function(item, selector, selector2) {
		var id = $(item).data('id');
		console.log(id);
		console.log(item);
		console.log(selector);
		console.log(selector2);
		// $(item).parent().parent().parent().parent().parent().parent().parent().remove();
		// file.docFile = {};
		//console.log(filesEdit.currentSelected);
		$(selector + ' .contract-file-upload').show();
		$(selector2).hide();
	},
	reIndex: function() {
		console.log("reindex");
		// refixe les numéros des tableaux
		var that = this;
		$.each(that.currentSelected, function(i, elem) {
			// var sel = '#uploader_files_' + i;
			var sel = '.files-list:eq( '+i+' )'; 
			console.log(sel);
			$(sel + ' .file-count').html(parseInt(i+1));
			$(sel).attr('id', '#uploader_files_' + i);
			// désaffiche la titre et la date de signature pour le 1er fichier de catégorie "contrat" à upload		
			if ( that.subFolder == '3' && i == 0 && that.forSubcontract == false ) {
				$(sel + ' form[name="import_file_infos_form"]').hide();
			}
		});
	},
	renderFiles: function(file, selector) {
		console.log('renderFiles');
		console.log(file, selector);
		var that = this;
		// restaure le fichier PDF
		if ( typeof(file.pdfFile) !== 'undefined' ) {
			this.renderFile(file.pdfFile, 'pdf', selector + ' form[name="import_pdf_form"]', selector + ' form[name="already_imported_pdf_form"]');
		}

		// restaure le fichier DOC/DOCX
		if (typeof(file.docFile) !== 'undefined') {
			this.renderFile(file.docFile, 'doc', selector + ' form[name="import_doc_form"]', selector + ' form[name="already_imported_doc_form"]');
		}

		// restaure la date
		if (( typeof(file.effective_date) !== 'undefined' ) && (file.effective_date != '')) {
			$(selector + ' form[name="import_file_infos_form"] input[name="import_file_infos_date"]').val(file.effective_date);
			// var date_range_start = moment(file.effectiveDate, dateRangePickerLanguage.format).format(translate.getText.date_format_moment);
			// var date_range_start = file.effective_date;
			// $(selector + ' form[name="import_file_infos_form"] input[name="import_file_infos_date"]').data('daterangepicker').setStartDate(date_range_start);
		}
		
		// restaure le titre
		if ( typeof(file.title) !== 'undefined' ) {
			$(selector + ' form[name="import_file_infos_form"] input[name="import_file_infos_title"]').val(file.title);
		}
		
		if ( (typeof(file.novation) !== 'undefined') && (file.novation != null) ) {
			console.log(file.novation.third_party_id);
			$(selector + ' form[name="import_file_infos_form"] select[name="third_party_out"]').val(file.novation.third_party_id).trigger("chosen:updated");
		}

		$(selector + ' form[name="import_file_infos_form"] input').change(function() {
			index = $(this).data('index');
			that.addFileInfo(index);
		});

		$(selector + ' form[name="import_file_infos_form"] select').change(function() {
			index = $(this).data('index');
			that.addFileInfo(index);
		});

	},
	renderFile: function(file, type, selector, selector2) {
		// console.log('renderFile');
		// console.log(file, selector, selector2);
		var that = this;
		var path = '/assets/apps/ContractDrive/templates/';
		if (typeof(file.name) !== 'undefined') {
			console.log('deja uploadé');
			$(selector + ' .contract-file-upload').hide();
			var data = {'file' : file, 'translate' : translate};
			var content = getTemplate(path + 'files-row.html', data);
			$(selector2 + ' .imported_files ul.jFiler-items-list').append(content);
			$(selector2).show();
		}

		this.initDeleteFile(selector, selector2);
	},
	activeJConfirmButtons: function(inOut) {
		if ( inOut ) {
			this.js_confirm.buttons.close.enable();
			this.js_confirm.buttons.validate.enable();
		} else {
			this.js_confirm.buttons.close.disable();
			this.js_confirm.buttons.validate.disable();
		}
	},
	updateImportedFilesMessage: function(tot) {
		if ( tot > 0 ) {
			$('#no_imported_files').hide();
		} else {
			$('#no_imported_files').show();
		}
	},
	returnSelection: function() {
		this.parent.selected = this.currentSelected;
		this.parent.toRemove = this.toRemove;
		if ( this.callback != null ) {
			console.log(this.callback);
			eval(this.callback);
		}
	}

}