<?

class audio_normalization {

	private $sql;


	public $files_groupped;

	public $all_files;

	public function __construct($data, $files_groupped, $all_files) {
		$this->data = $data;

		$this->files_groupped = $files_groupped;
		$this->all_files = $all_files;
	}

	public function initial_check($paths) {
		$self = $this;

		foreach($paths as $path) {
			if(!$files->is_readable($path)) {
				$files->picker($path, true, false, function($result) {
					$self->initial_check($paths);
				});
				return false;
			}
		}
		$this->find_normalization_parameters();
	}

	public function calculate_normalization($list) {
		$list = $files->partition_by_parent_folder($list, 'path');
		foreach($list as $path => $folder) {
			$mean_value = 0;
			$max_mean_value = 0;
			foreach($folder as $item) {
				$mean_volume = $object->strings->split($item['audio_level'], ' dB')[0];
				$max_volume = $object->strings->split($item['max_audio_level'], ' dB')[0];

				$mean_value = $mean_value + $mean_volume;
				$max_mean_value = $max_volume + $max_mean_value;
			}

			$mean_value = $mean_value / $folder->length;
			$max_mean_value = $max_mean_value / $folder->length;

			$adjustment = $this->set_audio_level - $mean_value;
			$adjustment = (-$adjustment);

			$this->save_adjustments($path, $adjustment);
		}
		$object->send('app.loading.hide(data)', ['data' => NULL]);	
	}

	public function save_adjustments($path, $adjustment) {
		$query = 'SELECT * FROM episodes WHERE path LIKE ?';
		$episodes = $this->data->get_rows($query, ['%'.$path.'%']);

		foreach($episodes as $episode) {
			$v = [
				'id' => $episode['id'],
				'adjustment_level' => $adjustment
			];

			$insert = $this->data->statement->generate($v, 'episodes');
			$this->data->_($insert, $v);
		}
	}

	public $set_audio_level = (-27);

	public function find_normalization_parameters() {
		$files_groupped = $this->files_groupped;
		$results = [];
		$self = $this;
		$completed_callback = function() {
			$list = [];
			foreach($results as $key => $results_group) {
				foreach($results_group as $index => $audio_level_information) {
					$item = [
						'audio_level' => $audio_level_information['audio_level'],
						'max_audio_level' => $audio_level_information['max_audio_level'], 
						'id' => $audio_level_information['id']
					];

					$insert = $self->data->statement->generate($item, 'episodes');
					$self->data->_($insert, $item);

					$list[] = $audio_level_information;
				}
			}
			$self->calculate_normalization($list);
		};

		$wrap = async function($file_group) {
			$media->operations->find_audio_levels($file_group, function($audio_levels) {
				$results[] = $audio_levels;
	
				if($results->length == $files_groupped->length) {
					$object->once($completed_callback);
				}
			}, function($progress) {
				$object->send('app.set_progress(data)', ['data' => $progress]);	
			});
		};
		foreach($files_groupped as $file_group) {
			$wrap($file_group);
		}
	}
}

?>