var inventory = [];
var allItems = [];
var focuson = false

$('.clothes').each(function(){
	var children = $(this).children()
	var name = $(this).attr('id');
	$(children).css('background-image', 'url("http://localhost/screenfivem/images/inventaire/clothes/' + name + '.png")')
})

function refreshInventory(){
	fetch(`http://spyoo_inventory/refreshInventory`, {
		method: 'POST',
		headers: {
			'Content-Type': 'application/json; charset=UTF-8',
		},
		body: JSON.stringify({})
		}).then(resp => resp.json()).then(resp => console.log(''));
}

function showError(error, duration){
	$('#msg_error').text(error)
	$('#error').show(500);
	setTimeout(function(){
		$('#error').hide(500)
	}, duration)
}

function useItem(slotTaken, slot){
	if (slotTaken[slot]){
		var item = slotTaken[slot][0];
		var dataNumber = slotTaken[slot][1];
		fetch(`http://spyoo_inventory/useItem`, {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json; charset=UTF-8',
			},
			body: JSON.stringify({
				item:item,
				slot:slot,
				dataNumber:dataNumber
			})
		}).then(resp => resp.json()).then(resp => console.log(''));
	}
}

function renameItem(slotTaken, slot, newLabel){
	if (slotTaken[slot]){
		var item = slotTaken[slot][0];
		var dataNumber = slotTaken[slot][1];
		fetch(`http://spyoo_inventory/renameItem`, {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json; charset=UTF-8',
			},
			body: JSON.stringify({
				item:item,
				dataNumber:dataNumber,
				newLabel:newLabel
			})
		}).then(resp => resp.json()).then(resp => console.log(''));
	}
}

function movedItem(item, slot, dataNumber){
	$.post('http://spyoo_inventory/movedItem', JSON.stringify({
		item:item,
		slot:slot,
		dataNumber:dataNumber
	}));
}

function afficherMenu(inventory, allItems){
	var maxSlot = 37
	$('#items').html('');
	$('#menuItem').remove()
	var slotTaken = [];
	for(i = 1; i < maxSlot; i++){
		var slot = $(
			`<div id='slot-`+i+`' class='item' data-slot='`+i+`'></div>`
		)
		$('#items').append(slot);
		if (i < 10){
			$('#slot-' + i).append(`
				<div class="numero_slot">`+i+`</div>
			`)
		}
	}

	var keys = Object.keys(inventory)

	$(keys).each(function(key, item){
		var $this = inventory[item]
		if ($this.length === undefined){
			if ($this.slot){
				slotTaken[$this.slot] = true
			}
		} else {
			for(i = 0; i < $this.length; i++){
				if ($this[i].slot){
					slotTaken[$this[i].slot] = true
				}
			}
		}
	})

	$(keys).each(function(key, item){
		var $this = inventory[item]
		if ($this.length === undefined){
			if (($this.slot) && (slotTaken[$this.slot] === true)){
				var slot = $this.slot
			} else {
				for(i = 1; i < maxSlot; i++){
					var slot = i
					if (slotTaken[i] === undefined){
						movedItem(item, i, false)
						break
					}
				}
			}
			$('#slot-' + slot).append(`
				<div id='`+item+`' class='item_img' style='background-image: url("http://localhost/screenfivem/images/inventaire/items/`+item+`.png")'></div>
			`)
			$('#slot-' + slot).addClass('item_movable')
			slotTaken[slot] = [ item, false ]
		} else {
			for(i = 0; i < $this.length; i++){
				var $itemData = $this[i]
				if (($itemData.slot) && (slotTaken[$itemData.slot] === true)){ 
					var slot = $itemData.slot
				} else {
					for(x = 1; i < maxSlot; x++){
						var slot = x
						if (slotTaken[x] === undefined){
							movedItem(item, x, i)
							break
						}
					}
				}
				var label = allItems[item].label
				if ($itemData.data.label){
					label = $itemData.data.label
				}
				$('#slot-' + slot).append(`
					<div id='`+item+`' class='item_img' style='background-image: url("http://localhost/screenfivem/images/inventaire/items/`+item+`.png")'></div>
				`)
				$('#slot-' + slot).append(`
					<div class="div_rename_item"><i class="fa-solid fa-pencil rename_item"></i></div>
				`)
				$('#slot-' + slot).addClass('item_movable')
				slotTaken[slot] = [ item, i ]
			}
		}
	})

	$('.item_movable').draggable({
		helper: 'clone',
		revert: 'invalid',
		containment: '#myInventory',
		start: function( event, ui ){
			$(ui.helper).css('width', '75px')
			$(ui.helper).css('height', '75px')
		}
	});

	$('.item').droppable({
		drop: function(event, ui){
			var oldSlot = ui.draggable.attr('data-slot');
			var newSlot = $(this).attr('data-slot')
			var item = slotTaken[oldSlot][0]
			var uniqueItem = slotTaken[oldSlot][1]
			if (slotTaken[newSlot] === undefined){
				slotTaken[oldSlot] = undefined
				slotTaken[newSlot] = [ item, uniqueItem ]
				movedItem(item, newSlot, uniqueItem)
				refreshInventory()
			} else {
				if (newSlot != oldSlot){
					showError('Ce slot est déjà utilisé !', 3000)
				}
			}
		}
	});

	$('.item').on('dblclick', function(){
		var slot = $(this).attr('data-slot');
		useItem(slotTaken, slot);
	})

	$('.item').on('mouseover', function(){
		var slot = $(this).attr('data-slot')
		if (slotTaken[slot]){
			var item = slotTaken[slot][0]
			var pos = slotTaken[slot][1]
			var label = allItems[item].label
			if (pos !== false){
				if (inventory[item][pos].data.label){
					label = inventory[item][pos].data.label
				}
			}
			$('#infoItem').html('')
			$('#infoItem').append(`
				<div>Nom : `+ label +`</div>
			`)
			if (pos === false){
				$('#infoItem').append(`
					<div>Quantité : ` + inventory[item].quantity + `</div>
				`)
			}

			if (pos !== false){
				if (inventory[item][pos].data.durability){
					$('#infoItem').append(`
						<div>Durabilitée : `+ inventory[item][pos].data.durability +` / 100</div>
					`)
				}
			}
		} else {
			$('#infoItem').html('')
		}
	})

	$('.item').mousedown(function(event){
		switch (event.which){
			case 3:
				var slot = $(this).attr('data-slot')
				$('#menuItem').remove()
				var X = event.pageX
				var Y = event.pageY
				if (slotTaken[slot]){
					$('#main').append(`
						<div id="menuItem">
							<div id="give">Donner</div>
							<div id="drop">Jeter</div>
							<div id="destroy">Détruire</div>
						</div>
					`)
					$('#menuItem').css('top', Y+'px')
					$('#menuItem').css('left', X+'px')

					$('#give').on('click', function(){
						console.log('give')
					})

					$('#drop').on('click', function(){
						console.log('drop')
					})

					$('#destroy').on('click', function(){
						console.log('destroy')
					})

				}
			break;
		}
	});

	$('.rename_item').on('click', function(){
		focuson = true
		var slot = $(this).parent().parent().attr('data-slot')
		var labelActuel = $(this).parent().text()
		$('#main').append(`
			<input type="text" class="absolute-center input-text" placeholder="Comment souhaitez-vous renommer cet item ?">
		`)
		$('.input-text').focus()
		$('.input-text').val(labelActuel)
		$('input').keydown(function(key){
			if (key.which == 13){
				var newLabel = $('.input-text').val()
				$('.input-text').remove()
				if (newLabel.length > 0){
					renameItem(slotTaken, slot, newLabel)
					refreshInventory()
				}
			}
		})		
	})
}

$(function () {
	function displayMyInventory(bool){
		if (bool){
			$('#main').show();
			focuson = false
		} else {
			$('#main').hide();
			$('#error').hide();
		}
	}
	displayMyInventory(false)
	window.addEventListener('message', function(event){
		var item = event.data;
		if (item.type === 'myInventory'){
			displayMyInventory(true)
			inventory = item.inventory
			allItems = item.items
			afficherMenu(inventory, allItems)
		}
		if (item.type === 'close'){
			displayMyInventory(false)
			$('.input-text').remove()
			inventory = [];
		}
		$(document).keydown(function(key){
			if (((key.which == 27) || (key.which == 112) || (key.which == 8) || (key.which == 73)) && (focuson === false)){
				$.post('http://spyoo_inventory/NUIClose', JSON.stringify({}));
			}
		})
	})
})
	