angular
	.module('dating.directives.audioMessage', [])
	.controller('AudioMessageCtrl', function ($scope, $rootScope, $interval, globalParamsService) {
		var audioMessageCtrl = this;
		var GLOBALS = globalParamsService.GLOBALS;
		audioMessageCtrl.upgradeUrl = GLOBALS.audioMessageUpgradeUrl;
		audioMessageCtrl.audioMessageFS = GLOBALS.audioMessageFS;
		var mediaRecorder;
		var audioChunks = [];
		var recordingInterval;
		var maxRecordingTime = 15; // Maximum recording time in seconds
		var checkInterval;

		function getCssVariable(variable) {
			return getComputedStyle(document.documentElement).getPropertyValue(variable).trim();
		}

		function formatTime(seconds) {
			var secs = seconds % 60;
			return '00:' + (secs < 10 ? '0' : '') + secs;
		}

		var waveColor = getCssVariable('--wave-color') || 'violet';
		var progressColor = getCssVariable('--progress-color') || 'purple';
		var cursorColor = getCssVariable('--cursor-color') || 'blue';
		var wavesurfer;
		audioMessageCtrl.wavesurferId = 'waveform' + audioMessageCtrl.messageId;
		function initWaveSurfer() {
			if (document.getElementById('waveform' + audioMessageCtrl.messageId)) {
				wavesurfer = WaveSurfer.create({
					container: '#' + audioMessageCtrl.wavesurferId,
					waveColor: waveColor,
					progressColor: progressColor,
					cursorColor: cursorColor,
					height: 40,
					barWidth: 3,
					barGap: 3,
					barRadius: 3,
					barHeight: 3
				});

				$scope.isRecording = false;
				$scope.audioAvailable = false;
				$scope.isPlaying = false;
				$scope.recordingTime = 0;
				$scope.formattedTime = formatTime(0);
				audioMessageCtrl.imagesUrl = GLOBALS.baseUrl + '/styles/images/audio-message/';

				navigator.mediaDevices
					.getUserMedia({ audio: true })
					.then(function (stream) {
						mediaRecorder = new MediaRecorder(stream);

						mediaRecorder.ondataavailable = function (event) {
							audioChunks.push(event.data);
						};

						mediaRecorder.onstop = function () {
							var audioBlob = new Blob(audioChunks, { type: 'audio/mp3' });
							var audioUrl = URL.createObjectURL(audioBlob);
							wavesurfer.load(audioUrl);
							$scope.audioAvailable = true;
							audioChunks = [];
							$scope.recordingTime = 0; // Reset recording time
							$scope.formattedTime = formatTime(0);
							if (recordingInterval) {
								$interval.cancel(recordingInterval);
							}
							$scope.$applyAsync();
							$rootScope.$broadcast('audioMessageAvailable');
						};
					})
					.catch(function (error) {
						console.error('Error accessing media devices.', error);
					});

				$scope.startRecording = function () {
					if (!mediaRecorder) {
						initWaveSurfer();
						return;
					}
					if (mediaRecorder.state === 'inactive') {
						mediaRecorder.start();
						$scope.isRecording = true;
						$scope.audioAvailable = false;
						$scope.recordingTime = 0; // Reset recording time
						$scope.formattedTime = formatTime(0);
						recordingInterval = $interval(function () {
							$scope.recordingTime++;
							$scope.formattedTime = formatTime($scope.recordingTime);
							if ($scope.recordingTime >= maxRecordingTime) {
								$scope.stopRecording(); // Auto-stop recording
							}
						}, 1000);
						$scope.$applyAsync();
					}
				};

				$scope.stopRecording = function () {
					if (mediaRecorder.state === 'recording') {
						mediaRecorder.stop();
						$scope.isRecording = false;
						if (recordingInterval) {
							$interval.cancel(recordingInterval);
						}
						$scope.$applyAsync();
					}
				};

				$scope.playAudio = function () {
					$scope.isPlaying = true;
					wavesurfer.play();
				};

				$scope.pauseAudio = function () {
					$scope.isPlaying = false;
					wavesurfer.pause();
				};

				$scope.deleteAudio = function () {
					wavesurfer.stop();
					wavesurfer.empty();
					$scope.audioAvailable = false;
					$scope.isPlaying = false;
					$scope.recordingTime = 0;
					$scope.formattedTime = formatTime(0);
					$rootScope.$broadcast('audioMessageRemoved');
					$scope.$applyAsync();
				};

				wavesurfer.on('finish', function () {
					$scope.isPlaying = false;
					$scope.$applyAsync();
				});

				if (checkInterval) {
					$interval.cancel(checkInterval);
				}
			}
		}
		checkInterval = $interval(initWaveSurfer, 100);
	})
	.directive('audioMessage', function () {
		return {
			restrict: 'E',
			controller: 'AudioMessageCtrl',
			controllerAs: 'audioMessageCtrl',
			bindToController: true,
			scope: {
				messageId: '@'
			},
			templateUrl: globalParams.templateUrls.directives.audio_message
		};
	});
