module.exports.getYear = function() {
	let dt = new Date();
	return dt.getFullYear();
};

module.exports.logout = function() {
	localStorage.removeItem('user_detail');
	localStorage.removeItem('user_jwt');
	localStorage.removeItem('login_redirect');
    window.location.replace(ENV.APP_URL + 'login');
};

module.exports.tableCall = function(url, form, recall = 0, path = 'list', append = true) {
	if (recall <= 3) {

	return form.get(
		ENV.API_URL + url, 
		{
			'Authorization': 'Bearer '+ TOKEN,
			'App-Key': ENV.APP_KEY
		}
		).then(response => {
			if (append) {
				let query_string = response.query_string ?  path + '?' + response.query_string : path;
				window.history.replaceState('', '', query_string);
			}
			return response
		})
		.catch(function (error) {
			if(error.response) {
				if (recall >= 3 && error.response.status == 401) {
					module.exports.logout();
				}
				console.log(recall++);
				return module.exports.tableCall(url, form, recall++, path, append);
			}
		});
	}
};

module.exports.getCall = function(url, form, recall = 0) {
	if (recall <= 3) {
	return form.get(
		ENV.API_URL + url, 
		{
			'Authorization': 'Bearer '+ TOKEN,
			'App-Key': ENV.APP_KEY
		}
		).then(response => {
			return response
		})
		.catch(function (error) {
			if(error.response) {
				if (recall >= 3 && error.response.status == 401) {
					module.exports.logout();
				}
				console.log(recall++);
				return module.exports.getCall(url, form, recall++);
			}
		});
	}
};

module.exports.validCheck = function(url, form, ref_inputs) {
	return new Promise((resolve, reject) => {
		form.post(
			ENV.API_URL + url, 
			{
				'Authorization': 'Bearer '+ TOKEN,
				'App-Key': ENV.APP_KEY
			}
		).then(data => {
			resolve(true);
		})
		.catch(error => {
			let ref_inputs_data = ref_inputs;
			let error_status = true;
			Object.keys(ref_inputs_data).forEach(function (key) {
				if (form.errors.has(ref_inputs_data[key])) {
					error_status = false;
				}
			});
			if (!error_status) {
				resolve(false);
			}
			else {
				resolve(true);
				form.errors.clear();
			}
		});
	});
};

module.exports.onComplete = function(url, form, method) {
	return new Promise((resolve, reject) => {
		form[method](
			ENV.API_URL + url, 
			{
				'Authorization': 'Bearer '+ TOKEN,
				'App-Key': ENV.APP_KEY
			}
		).then(data => {
			resolve(data);
		})
		.catch(error => {
			reject(false);
		});
	});
};

module.exports.getURLParam = function(key) {
	const queryString = require('query-string');
	const parsed = queryString.parse(location.search);
	return parsed[key];
};

module.exports.getStringParam = function(key, url) {
 	url = url.split('?');
 	url = url[1] ? url[1] : url[0];

 	const queryString = require('query-string');
	const parsed = queryString.parse('?' + url);
	return parsed[key];
};

module.exports.getKey = function(set = [], type = 'key', null_type = 'text') {
 	let return_data = [];

 	if (set.length > 0) {
	 	set.forEach(function(element, index) {
	 		return_data.push(element[type] ? element[type] : element[null_type]);
	 	});
	 }
    return return_data;
};

module.exports.autoCompleteKeyConvert = function(set = [], tag = '') {
	let return_date = [];
	set.forEach(function(element, index) {
		return_date.push({
			'id': element.id,
			'hash_id': element.hash_id,
			'row': element,
			'text': element.name,
			'tiClasses':[ "ti-valid" ]
		});
	});

	return return_date;
};

module.exports.initFormArray = function(set, form_field) {
	let return_date = [];

	if (form_field[0]) {
		form_field.forEach(function(element, index) {
			return_date.push(module.exports.filterByProperty(set, 'id', element))
		});
	}
	return return_date;
};

module.exports.selectStructure = function(set = [], id = '', value = '', other = null, other_2 = null) {
	let return_set = {
		'data': [],
		'actual_data': set
	};
	set.forEach(function(element, index) {
        return_set.data.push({
	 		'key': element[id],
	        'value': element[value] + ' ' + (other ? '(' + element[other][0].name + ')' : '') + ' ' + (other_2 ? '(' + element[other_2][0].name + ')' : '')
        });
	});

	return return_set;
};

module.exports.returnAray = function(set) {
	if (set !== undefined && set !== null) {
    	set = Array.isArray(set) ?  set : [set];
    }
	else {
		set = [];
	}
    return set;
};


// module.exports.postCall = function(url, params = {}) {
// 	return axios.post(
// 		ENV.API_URL + url, params, {
// 			headers: {
// 				'Authorization': 'Bearer '+ TOKEN
// 			}
// 		}).then(response => {
// 			return response.data
// 		})
// 		.catch(function (error) {
		
// 		});
// };

// module.exports.putCall = function(url, params = {}) {
// 	return axios.put(
// 		ENV.API_URL + url, params, {
// 			headers: {
// 				'Authorization': 'Bearer '+ TOKEN
// 			}
// 		}).then(response => {
// 			return response.data
// 		})
// 		.catch(function (error) {
		
// 		});
// };



// module.exports.setpUpdate = function(url, ref_inputs, form) {
// 	return new Promise((resolve, reject) => {
// 		form.put(
// 			ENV.API_URL + url, {
// 			headers: {
// 				'Authorization': 'Bearer '+ TOKEN
// 			}
// 		}).then(data => {
// 			resolve(true);
// 		})
// 		.catch(error => {
// 			let ref_inputs_data = ref_inputs.split(',');
// 			let error_status = true;
// 			Object.keys(ref_inputs_data).forEach(function (key) {

// 				// variation_rule
// 				if(typeof form[ref_inputs_data[key]] === 'object') {
// 					if (ref_inputs_data[key] == 'variation_rule' && form[ref_inputs_data[key]].type) {
// 						if (form[ref_inputs_data[key]].type == 1) {
// 							let set = form[ref_inputs_data[key]].content.detail;
// 							set.forEach(function(element, index) {
// 								let set_key = Object.keys(element);
// 								set_key.forEach(function(element_2, index_2) {
// 									if (form.errors.has(ref_inputs_data[key] + '.content.detail.' + index + '.' + element_2)) {
// 										error_status = false;
// 									}
// 								});
// 							});
// 						}
// 						else {
// 							let set = form[ref_inputs_data[key]].content.detail;

// 							set.forEach(function(element, index) {
// 								let set_2 = element.content.detail;
// 								set_2.forEach(function(element_2, index_2) {
// 									let set_key = Object.keys(element_2);
// 									set_key.forEach(function(element_3, index_3) {
// 										if (form.errors.has(ref_inputs_data[key] + '.content.detail.'  + index + '.content.detail.' + index_2 + '.' + element_3)) {
// 											error_status = false;
// 										}
// 									});
// 								});
// 							});
// 						}
// 					}
// 				}

// 				if (Array.isArray(form[ref_inputs_data[key]])) {
// 					let set = form[ref_inputs_data[key]];
// 					set.forEach(function(element, index) {
// 						let set_key = Object.keys(element);
// 						set_key.forEach(function(element_2, index_2) {
// 							if (form.errors.has(ref_inputs_data[key] + '.' + index + '.' + element_2)) {
// 								error_status = false;
// 							}
// 						});
// 					});
// 				}
// 				else {
// 					if (form.errors.has(ref_inputs_data[key])) {
// 						error_status = false;
// 					}
// 				}
// 			});
// 			if (!error_status) {
// 				resolve(false);
// 			}
// 			else {
// 				resolve(true);
// 				form.errors.clear();
// 			}
// 		});
// 	});
// };






module.exports.filterByProperty = function(array, prop, value) {
    for(var i = 0; i < array.length; i++){
        var obj = array[i];
        for(var key in obj){
            if(typeof(obj[key] == "object")){
                var item = obj[key];
                if(key == prop && item == value){
                    return obj;
                }
            }
        }
    }    
};



module.exports.arrayConvert = function(set = []) {
	let return_date = [];

	set.forEach(function(element, index) {
		return_date.push({
			'id': element,
			'name': element
		});
	});
	return return_date;
};



module.exports.imageBase64 = function(imgs) {
	let num = 1;
	let base = [];
	let count = imgs.length;

	return new Promise((resolve, reject) => {
		Array.from(imgs).forEach(file => { 
			let reader = new FileReader();
			reader.onload = () => {
				base.push(reader.result);
				if (num >= count) {
					resolve(base);
				}
				num++;
			};
			reader.readAsDataURL(file);
		})
	});
};

module.exports.toastedMessage = function(type, object, key) {
	let message = '';
	let value = [
        {att: object},
        {att: key},
    ];

	if (type == 'create') {
		message = Sprintf(module.exports.lang('have_been_successfully_created'), {value: value});
	}
	else if(type == 'edit') {
		message = Sprintf(module.exports.lang('have_been_successfully_updated'), {value: value});
	}

	Vue.toasted.success(message, {
		icon : {
			name : 'check',
		}
	}).goAway(3500);
};

module.exports.lang = function(code) {
	let lang_selected = localStorage.getItem('lang_selected');
	if (lang_selected == 'cn') {
		return Cn[code];
	}
	else {
		return En[code];
	}
};

module.exports.selectOptionConvert = function(set = [], id = '', value = '', other = null, other_2 = null) {
	let return_set = [];
	set.forEach(function(element, index) {
        return_set.push({
	 		'key': element[id],
	        'value': element[value] + ' ' + (other ? '(' + element[other][0].name + ')' : '') + ' ' + (other_2 ? '(' + element[other_2][0].name + ')' : '')
        });
	});
	return return_set;
};



module.exports.filterOut = function(set = [], out = []) {
	let filter_set = [];

	set.forEach(function(element, index) {
		let allow = true;
		out.forEach(function(element_out, index_out) {
			if (element.id == element_out) {
				allow = false;
			}
		});
		if (allow == true) {
			filter_set.push(element);
		}
	});

	return filter_set;
};

module.exports.videoBase64 = function(video) {
	let num = 1;
	let base = [];
	let count = video.length;

	return new Promise((resolve, reject) => {
		Array.from(video).forEach(file => { 
			let reader = new FileReader();
			reader.onload = () => {
				base.push(reader.result);
				if (num >= count) {
					resolve(base);
				}
				num++;
			};
			reader.readAsDataURL(file);
		})
	});
};

module.exports.errorData = function(data) {
	let error_data = [];
	let error_message = '';
 	Object.keys(data).forEach(function(key) {
		error_data.push(data[key]);
 	});
 	error_message = error_data.join('<br>');
 	return error_message;
};

module.exports.timeSince = function(date) {
  var seconds = Math.floor((new Date() - date) / 1000);

  var interval = Math.floor(seconds / 31536000);

  if (interval > 1) {
    return 'Active ' + interval + ' Years Ago';
  }
  interval = (seconds / 2592000);
  if (interval > 1) {
    return 'Active ' + Math.floor(interval) + ' Months Ago';
  }
  interval = (seconds / 86400);
  if (interval > 1) {
    return 'Active ' + Math.floor(interval) + ' Days Ago';
  }
  interval = (seconds / 3600);
  if (interval  > 1) {
    return 'Active' + Math.floor(interval) + ' Hours Ago';
  }
  interval = (seconds / 60);
  if (interval > 1) {
    return 'Active ' + Math.floor(interval) + ' Minutes Ago';
  }
  return 'Active ' + Math.floor(seconds) + ' Seconds Ago';
};

module.exports.shortenNumber = function(num) {
	let nformat = 0;

	if (num < 1000) {
        nformat = number_format(num);
    }
    else if (num < 1000000) {
        // Anything less than a million
        nformat = (num / 1000).toFixed(1) + 'k';
    } 
    else if (num < 1000000000) {
        // Anything less than a billion
        nformat = (num / 1000000).toFixed(3) + 'm';
    } 
    else {
        // At least a billion
        nformat = (num / 1000000000, 3).toFixed(3) + 'b';
    }
    
    return nformat;
};

// public static function shortenNumber($number){
//         if ($number < 1000) {
//             $nformat = number_format($number);
//         }else if ($number < 1000000) {
//             // Anything less than a million
//             $nformat = number_format($number/1000,1) . 'k';
//         } else if ($number < 1000000000) {
//             // Anything less than a billion
//             $nformat = number_format($number / 1000000, 3) . 'm';
//         } else {
//             // At least a billion
//             $nformat = number_format($number / 1000000000, 3) . 'b';
//         }
        
//         return $nformat;
//     }


// module.exports.selectStructureNonDB = function(set = []) {
// 	let return_set = {
// 		'data': [],
// 		'actual_data': set.data
// 	};
// 	set.data.forEach(function(element, index) {
//         return_set.data.push({
// 	 		'key': element,
// 	        'value': element
//         });
// 	});
// 	return return_set;
// };



module.exports.httpConvert = function(params) {
	let query_string = '';
	Object.keys(params).forEach(function(element, index) {
		if( Object.prototype.toString.call( params[element] ) === '[object Array]' ) {
			if (params[element][0]) {
				params[element].forEach(function(element_2, index_2) {
					query_string += element + '[]=' +  element_2 + '&';
				});
			}
		}
		else {
			if (params[element]) {
				console.log(params[element]);
				query_string += element + '=' +  params[element] + '&';
			}
		}
	});
	return query_string;
};


// 	return filter_set;
// };

// module.exports.pluckID = function(set = []) {
// 	let return_set = [];
// 	set.forEach(function(element, index) {
// 		return_set.push(element.id);
// 	});
// 	return return_set; 
// };








// module.exports.dateConvert = function(date) {
// 	let return_date = '';
// 	if (date) {
// 		let parts = date.split('-');
// 		return_date = new Date(parts[2], parts[1] - 1, parts[0]); 
// 	}
//   	return return_date;
// };

// module.exports.foreachErrorToasted = function(data) {
// 	let error_data = module.exports.errorData(data);
// 	error_data.forEach(function(element, index) {
// 	Vue.toasted.error(element, {
//     icon : {
//     	name : 'close',
//     }
//     }).goAway(3500);

//  	});
// };







// module.exports.getURLParam = function(key) {
// 	const queryString = require('query-string');
// 	const parsed = queryString.parse(location.search);
// 	return parsed[key];
// };

// module.exports.returnAray = function(set) {
// 	if (set !== undefined) {
//     	set = Array.isArray(set) ?  set : [set];
//     }
// 	else {
// 		set = [];
// 	}
//     return set;
// };

// module.exports.autoCompleteKeyConvert = function(set = []) {
// 	let return_date = [];
// 	set.forEach(function(element, index) {
// 		return_date.push({
// 			'id': element.id,
// 			'row': element,
// 			'text': element.name,
// 			'tiClasses':[ "ti-valid" ]
// 		});
// 	});

// 	return return_date;
// };

// module.exports.formatNumber  = function(set, form_field) {
// 	if (form_field[0]) {
// 		form_field.forEach(function(num) {
// 			return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
// 		});
// 	}
// };