using UnityEngine;
using System.Collections;
using System;

#if UNITY_WSA && !UNITY_WSA_8_1 && !UNITY_EDITOR
using Windows.Phone.Devices.Notification;
using System.Threading.Tasks;
#endif

public static class VibrationHelper
{
	private static int vibId = 0;

	public static void Vibrate (int ms)
	{
		#if UNITY_EDITOR
		// No vibration in the editor
		#elif UNITY_WSA_8_1
		// No vibration on desktop
		#elif UNITY_WSA && !UNITY_WSA_8_1
		var id = ++vibId;
		VibrationDevice device = VibrationDevice.GetDefault();
		if (device != null) {
			device.Vibrate(TimeSpan.FromMilliseconds(ms));

		    // Run task to cancel vibration (this is an error in phone framework where the vibration does
		    // not stop after running the first time)
		    Task.Run(async () =>
		    {
				await Task.Delay(ms + 50);
				if (id == vibId) {
		        	VibrationDevice.GetDefault().Cancel();
		        }
		    });
		}
		#elif UNITY_ANDROID
		if (VibrationManager.HasVibrator () == true) {
			VibrationManager.Vibrate (ms);
		}
		#elif UNITY_IOS
		Handheld.Vibrate();
		#else
		throw new NotImplementedException("Vibration with custom time is not implemented on this platform");
		#endif
	}
}
