function useProperty(property = {}) {
	if (typeof property.load == "function") {
		return property;
	}

	property = JSON.parse(JSON.stringify(property || {}));

	const storage = window.useStorageJs();

	const currentSeasonOfDate = (date_moment) => {
		if (!property || !Object.keys(property).length) return null;
		const currentSeason =
			property.property_seasons?.filter((season) => {
				if (season.start_date && season.published) {
					return date_moment.isBetween(
						season.start_date,
						season.end_date,
						null,
						"[]",
					);
				}
			}) ?? [];
		return currentSeason[0];
	};

	const showMinimumStay = () => {
		const currentSeason = currentSeasonOfDate(window.$moment());
		if (currentSeason && currentSeason.minimum_stay)
			return currentSeason.minimum_stay;
		return property?.property_pricings
			? property.property_pricings.minimum_stay
			: 1;
	};

	const totalBedrooms = () => {
		let _total = 0,
			_arr_beds = [];

		if (property.property_house_configurations) {
			_arr_beds = property.property_house_configurations.filter(
				(room) => room.room_type.id === 1,
			);
			_total = _arr_beds.length;
		}
		return _total;
	};

	const propertyParse = (property) => {
		const getIcon = (name) => {
			name = name.toLowerCase();

			const icons = [
				{
					icon: "mdi-hand-wash",
					finds: ["clean", "sanitary"],
				},
				{icon: "mdi-moped", finds: ["delivery"]},
				{icon: "mdi-air-conditioner", finds: ["air"]},
				{
					icon: "mdi-wifi",
					finds: ["wireless", "wifi", "wi-fi", "internet"],
				},
				{icon: "mdi-pool", finds: ["outdoor pool"]},
				{icon: "mdi-stove", finds: ["stove"]},
				{icon: "mdi-leaf", finds: ["sustainability"]},
				{
					icon: "mdi-wheelchair-accessibility",
					finds: ["accessibility"],
				},
				{icon: "mdi-fridge", finds: ["refrigerator"]},
				{icon: "mdi-toaster-oven", finds: ["oven"]},
				{icon: "mdi-bed-double", finds: ["bedroom"]},
				{icon: "mdi-shower-head", finds: ["bathroom"]},
				{
					icon: "mdi-parking",
					finds: ["parking"],
				},
				{icon: "mdi-dishwasher", finds: ["dishwasher"]},
				{
					icon: "mdi-silverware-variant",
					finds: ["dishes", "cutlery"],
				},
				{icon: "mdi-ceiling-fan", finds: ["ceiling fan"]},
				{icon: "mdi-hvac", finds: ["gas heating"]},
				{icon: "mdi-silverware-fork-knife", finds: ["cookware"]},
				{icon: "mdi-shaker-outline", finds: ["cooking", "salt"]},
				{icon: "mdi-television", finds: ["tv"]},
				{icon: "mdi-smoke-detector", finds: ["smoke detector"]},
				{icon: "mdi-grass", finds: ["backyard"]},
				{icon: "mdi-balcony", finds: ["balcony"]},
				{icon: "mdi-fire-extinguisher", finds: ["fire extinguisher"]},
				{icon: "mdi-police-badge", finds: ["police"]},
				{icon: "mdi-medical-bag", finds: ["medical"]},
				{icon: "mdi-paw", finds: ["pets"]},
				{icon: "mdi-dog-side-off", finds: ["no pets"]},
				{icon: "mdi-cancel", finds: ["no parties"]},
				{icon: "mdi-smoking-off", finds: ["no smoking"]},
				{icon: "mdi-face-mask", finds: ["face mask"]},
				{icon: "mdi-lotion-plus", finds: ["sanitizer"]},
				{
					icon: "mdi-social-distance-2-meters",
					finds: ["social distancing"],
				},
				{
					icon: "mdi-account-switch",
					finds: ["contactless check-out"],
				},
				{icon: "mdi-table-furniture", finds: ["outdoor furniture"]},
				{icon: "mdi-grill", finds: ["outdoor barbecue"]},
				{icon: "mdi-spray-bottle", finds: ["enhanced cleaning"]},
				{icon: "mdi-medical-bag", finds: ["first aid"]},
				{icon: "mdi-beach", finds: ["beach"]},
				{icon: "mdi-account-multiple-outline", finds: ["couple"]},
				{icon: "mdi-grill", finds: ["bbq barbecue"]},
				{icon: "mdi-countertop", finds: ["kitchen"]},
				{icon: "mdi-elevator", finds: ["lift elevator"]},
				{icon: "mdi-coffee-maker", finds: ["coffee"]},
				{icon: "mdi-city", finds: ["city"]},
				{icon: "mdi-snowman", finds: ["snow"]},
				{icon: "mdi-sail-boat", finds: ["lake"]},
				{icon: "mdi-silo", finds: ["farm", "farmstay"]},
				{icon: "mdi-tractor", finds: ["rural"]},
				{icon: "mdi-glass-wine", finds: ["wineries"]},
				{icon: "mdi-tree-outline", finds: ["regional area"]},
				{icon: "mdi-book-outline", finds: ["outback"]},
				{icon: "mdi-ski", finds: ["skiing"]},
				{
					icon: "mdi-food-turkey",
					finds: ["epicurean"],
				},
				{icon: "mdi-surfing", finds: ["surfing"]},
				{icon: "mdi-ski-cross-country", finds: ["country"]},
				{icon: "mdi-alpha-a", finds: ["adventure"]},
				{icon: "mdi-caravan", finds: ["holiday"]},
				{
					icon: "mdi-forest",
					finds: ["nature", "bushwalking"],
				},
				{icon: "mdi-disc", finds: ["cd", "dvd"]},
				{
					icon: "mdi-seatbelt",
					finds: ["safety"],
				},
			];

			for (let icon of icons) {
				for (let ii in icon.finds) {
					const find = icon.finds[ii];
					if (name.includes(find)) {
						return icon.icon;
					}
				}
			}

			return "mdi-check";
		};

		/**
		 * "filters" items Define required attributes for property object.
		 * Each array item os formed by [attributeName, defaultValue, callback].
		 * If "attribute_name" does not exists or is undefined or false, will be replaced by "defaultValue".
		 * The "callback" para run over property attribute with itself as param then return the computed value.
		 * For intance:
		 * property.property_booking_reservations = callback(property.property_booking_reservations);
		 */

		const filters = [
			// Basic properties info
			[
				"properties",
				{},
				(properties) => {
					properties.property_rating =
						properties.property_rating || 0;

					properties.property_descriptions = {
						description: "",
						...properties.property_descriptions,
					};

					return properties;
				},
			],

			// Blocked dates
			[
				"blocked_dates",
				[],
				(blocked_dates) => {
					return blocked_dates.filter((v) => v);
				},
			],

			// Location address
			[
				"property_locations",
				{},
				(property_locations) => {
					return property_locations;
				},
			],

			// Basic informations list
			[
				"property_basic_informations",
				{},
				(property_basic_informations) => {
					property_basic_informations.items = [];

					if (
						property_basic_informations &&
						property_basic_informations?.id
					) {
						const name =
							property_basic_informations?.property_type?.name;
						if (name)
							switch (name.toLowerCase()) {
								case "house":
								case "cabin":
								case "farm stay":
								case "granny flat":
								case "bed and breakfast":
									property_basic_informations.items.push({
										icon: "mdi-home",
										name: property_basic_informations
											?.property_type?.name,
									});
									break;
								default:
									property_basic_informations.items.push({
										icon: "mdi-office-building",
										name: property_basic_informations
											?.property_type?.name,
									});
									break;
							}

						if (property.property_house_configurations) {
							property_basic_informations.items.push({
								icon: "mdi-bed-double",
								name: `${totalBedrooms()} Bedroom${
									totalBedrooms() !== 1 ? "s" : ""
								}`,
							});
						}

						property_basic_informations.items.push({
							id: property_basic_informations.property_type.id,
							icon: "mdi-account",
							name: `Maximum Guests: ${property_basic_informations.property_restrictions.maximum_guests}`,
						});

						if (showMinimumStay()) {
							property_basic_informations.items.push({
								icon: "mdi-calendar-month",
								name: `Minimum Stay:<br /> ${showMinimumStay()} night${
									showMinimumStay() !== 1 ? "s" : ""
								}`,
							});
						}

						if (
							property_basic_informations.property_restrictions
								.availability
						) {
							property_basic_informations.items.push({
								icon: "mdi-hand-pointing-up",
								name: "Available Immediately",
							});
						} else {
							property_basic_informations.items.push({
								icon: "mdi-calendar-alert",
								name: "Available On Request",
							});
						}
						if (property.property_linens?.linen) {
							property_basic_informations.items.push({
								icon: "mdi-bed-empty",
								name: `Linen Provided`,
							});
						}

						const petsUnify = [
							"pets",
							"pet friendly",
							"pets friendly",
							"pets allowed",
							// 'pets by request only',
						];
						const names = [
							"bathroom",
							"bedroom",
							"pool",
							"outdoor pool",
							"wireless internet",
							"Wi-Fi",
							"air-conditioning",
						];

						const amenities = property.property_amenities;

						if (amenities) {
							let amenitiesItems = [
								...new Set(
									amenities.map((el) => el?.name) || [],
								),
							];

							amenitiesItems
								.filter(
									(amenityItem) =>
										amenityItem &&
										names.includes(
											amenityItem.toLowerCase(),
										),
								)
								.forEach((amenityItem) => {
									property_basic_informations.items.push({
										name: amenityItem,
										icon: getIcon(amenityItem),
									});
								});

							if (
								amenities.filter(
									(el) => el?.amenity_category_id === 2,
								).length
							)
								property_basic_informations.items.push({
									name: "Accessibility Options",
									icon: getIcon("accessibility"),
								});

							if (
								amenities.filter(
									(el) => el?.amenity_category_id === 24,
								).length
							)
								property_basic_informations.items.push({
									name: "Sustainability Features",
									icon: getIcon("sustainability"),
								});

							if (
								amenitiesItems.some(
									(el) =>
										el &&
										petsUnify.includes(el.toLowerCase()),
								)
							)
								property_basic_informations.items.push({
									name: "Pet Friendly",
									icon: getIcon("pets"),
								});
						}
					}
					return property_basic_informations;
				},
			],

			// House configuration with icons
			[
				"property_house_configurations",
				[],
				(property_house_configurations) => {
					return property_house_configurations
						.filter((v) => v)
						.map((item, index) => {
							return {
								id: index,
								icon: getIcon(item.room_type.name),
								...item,
							};
						});
				},
			],

			// Holiday types with icons
			[
				"property_holiday_types",
				[],
				(property_holiday_types) => {
					return property_holiday_types
						.filter((v) => v)
						.map((item, index) => {
							return {
								id: item.id,
								icon: getIcon(item.name),
								...item,
							};
						});
				},
			],

			// Holiday suitables
			[
				"property_holiday_suitables",
				[],
				(property_holiday_suitables) => {
					return property_holiday_suitables
						.filter((v) => v)
						.map((item, index) => {
							return {
								id: item.id,
								icon: getIcon(item.name),
								...item,
							};
						});
				},
			],

			// Amenities with icons
			[
				"property_amenities",
				[],
				(property_amenities) => {
					property.property_holiday_suitables = property_amenities
						.filter((v) => v.amenity_category_id === 36)
						.map((item, index) => {
							return {
								id: item.id,
								icon: getIcon(item.name),
								...item,
							};
						});

					property.property_holiday_types = property_amenities
						.filter((v) =>
							[37, 38, 39].includes(v.amenity_category_id),
						)
						.map((item, index) => {
							return {
								id: item.id,
								icon: getIcon(item.name),
								...item,
							};
						});

					return property_amenities
						.filter((v) => v)
						.map((item) => {
							return {
								id: item.id,
								icon: getIcon(item.name),
								...item,
							};
						});
				},
			],

			// House rules with icons
			[
				"property_house_rules",
				[],
				(property_house_rules) => {
					return property_house_rules.filter((v) => v);
				},
			],

			// property images
			[
				"property_images",
				[],
				(property_images) => {
					// Test for nonexistent images
					// if (!import.meta.env.PROD) {
					//   property_images = (property_images || []).map((img, index) => {
					//     img.full_path_large = `https://source.unsplash.com/random?r=${img.id}-${index}`;
					//     img.full_path_medium = `https://source.unsplash.com/random?r=${img.id}-${index}`;
					//     return img;
					//   });
					// }

					return property_images.filter((v) => v);
				},
			],
		];

		for (const i in filters) {
			const [attr, defaultValue, callback] = filters[i];
			if (typeof property[attr] == "undefined") {
				property[attr] = defaultValue;
			}

			if (typeof callback == "function") {
				property[attr] = callback(property[attr] || defaultValue);
			}
		}

		property = {
			resume: {
				rooms: property.property_house_configurations.filter(
					(prop) => prop.room_type.id === 1,
				).length,
				bathrooms: property.property_house_configurations.filter(
					(prop) => prop.room_type.id === 2,
				).length,
			},
			...property,
		};

		return property;
	};

	property = propertyParse(property);

	return Vue.reactive({
		...property,

		async load(slug) {
			return new Promise(async (resolve, reject) => {
				this.notFound = false;
				this.loading = true;
				try {
					const property = window.useAxios({
						method: "get",
						url: `/guest/properties/${slug}`,
						headers: {SearchAndStayApiToken: null},
					});
					const {data} = await property.submit();
					const propertyData = propertyParse(data.data);
					resolve(propertyData);
					Object.entries(propertyData).forEach(([attr, value]) => {
						this[attr] = value;
					});
					this.ok = true;
				} catch (err) {
					this.notFound = true;
					this.ok = false;
					reject(err);
				}
				this.loading = false;
			});
		},
	});
}

window.useProperty = useProperty;
