/**
 * CCDN v1.4.18
 */

$(document).ready(function () {
	$('.update-embed-js').on('click', function () {
		let that = $(this);
		let url = that.data('update-url');

		/**
		 * Search Fields
		 */
		let kinopoiskIdField = $('#xf_' + configCCDN.kinopoisk_id_field);
		let ccdnIdField = $('#xf_' + configCCDN.ccdn_id_field);
		let imdbIdField = $('#xf_' + configCCDN.imdb_id_field);
		let worldArtIdField = $('#xf_' + configCCDN.world_art_id_field);

		let imdbId = '';
		if (imdbIdField.val() !== undefined) {
			imdbId = imdbIdField.val().replace('tt', '')
		}

		that.html(btnConditionText.search);
		$.post(url, {
			kinopoisk_id: kinopoiskIdField.val(),
			ccdn_id: ccdnIdField.val(),
			imdb_id: imdbId,
			news_id: newsIdCCDN,
			world_art_id: worldArtIdField.val(),
		}).done(function (response) {
			let title = $('#title');

			if (title.val().length === 0) {
				title.val(response.name);
			}

			let dle_v = parseInt(DLEConfig.version_id);

			if (response.set_short_desc && response.description) {
				let shortStory = $('#short_story');
				if (shortStory.froalaEditor !== undefined) {
					if (!shortStory.froalaEditor('html.get')) {
						shortStory.froalaEditor('html.set', response.description);
					}
				} else if (!shortStory.text()) {
					shortStory.text(response.description);
				}
			}

			if (response.set_description && response.description) {
				let fullStory = $('#full_story');
				if (fullStory.froalaEditor !== undefined) {
					if (!fullStory.froalaEditor('html.get')) {
						fullStory.froalaEditor('html.set', response.description);
					}
				} else if (!fullStory.text()) {
					fullStory.text(response.description);
				}
			}


			if (response.set_category) {
				for (let catId in response.category) {
					$('#category option[value="' + response.category[catId] + '"]').prop('selected', true)
				}
				if (dle_v >= 12) {
					$('#category').trigger('chosen:updated');
				} else {
					$('#category').trigger('liszt:updated');
				}
			}


			setData(configCCDN, 'embed_field', response.iframe_url);
			setData(configCCDN, 'kinopoisk_id_field', response.kinopoisk_id);
			setData(configCCDN, 'imdb_id_field', response.imdb_id);
			setData(configCCDN, 'world_art_id_field', response.world_art_id);
			setData(configCCDN, 'ccdn_id_field', response.id);

			setData(configCCDN, 'button_name', response.name);
			setData(configCCDN, 'button_origin_name', response.name_eng);
			setData(configCCDN, 'video_quality_field', response.quality);
			setData(configCCDN, 'video_voice_field', response.voiceActing);
			setData(configCCDN, 'video_first_voice_field', response.firstVoice);
			setData(configCCDN, 'button_country', response.country);
			setData(configCCDN, 'button_actors', response.actors);
			setData(configCCDN, 'button_director', response.director);
			setData(configCCDN, 'button_year', response.year);
			setData(configCCDN, 'button_rating_imdb', response.imdb);
			setData(configCCDN, 'button_rating_kinopoisk', response.kinopoisk);
			setData(configCCDN, 'button_rating_world_art', response.world_art);
			setData(configCCDN, 'button_poster', response.poster);
			setData(configCCDN, 'button_age', response.age);
			setData(configCCDN, 'button_genres', response.genre);
			setData(configCCDN, 'button_time', response.time);
			setData(configCCDN, 'button_premier', response.premier);
			setData(configCCDN, 'button_premier_rus', response.premier_rus);
			setData(configCCDN, 'button_trailer', response.trailer);
			setData(configCCDN, 'episode_count_field', response.episode_count);
			setData(configCCDN, 'serial_season_field', response.season);
			setData(configCCDN, 'serial_episode_field', response.episode);
			setData(configCCDN, 'collaps_franchise_ads_status_field', response.ads);
			setData(configCCDN, 'season_franchise_status', response.serial_status);

			setData(configCCDN, 'button_slogan', response.slogan);
			setData(configCCDN, 'button_screenwriter', response.screenwriter);
			setData(configCCDN, 'button_producer', response.producer);
			setData(configCCDN, 'button_operator', response.operator);
			setData(configCCDN, 'button_design', response.design);
			setData(configCCDN, 'button_editor', response.editor);
			setData(configCCDN, 'button_actors_dubbing', response.actors_dubl);
			setData(configCCDN, 'button_budget', response.budget);
			setData(configCCDN, 'button_fees_use', response.fees_use);
			setData(configCCDN, 'button_fees_world', response.fees_world);
			setData(configCCDN, 'button_fees_rus', response.fees_rus);
			setData(configCCDN, 'button_rate_mpaa', response.rate_mpaa);
			setData(configCCDN, 'button_trivia', response.trivia);
			setData(configCCDN, 'button_composer', response.composer);
			setData(configCCDN, 'button_custom_filed_description', response.description);
			setData(configCCDN, 'button_franchise_type', response.franchise_type);

			uploadField(configCCDN, 'button_download_poster', response.poster);

		}).fail(function (response) {
			DLEalert('Что-то пошло не так. Код ошибки: ' + response.status + '<br> Сообщение: ' + response.responseText, "Сообщение об ошибке!");
		}).always(function () {
			that.html(btnConditionText.normal);
		}).then(function () {
		});
	});
});

/**
 *
 * @param {object} config
 * @param {string} field
 * @param  data
 * @returns {boolean}
 */
function setData(config, field, data) {

	if (data === null || data === undefined) {
		return false;
	}

	if (field in config && config[field] !== null) {
		let customField = document.getElementsByName('xfield[' + config[field] + ']')[0];

		if (typeof customField === 'undefined') {
			return false;
		}

		customField.value = data;
		$(customField).trigger('change');

		if (customField.classList.contains('switch') && customField.checked !== data) {
			$(customField).trigger('click');
		}

		return true;
	}

	return false;
}

/**
 *
 * @param config
 * @param field
 * @param fileUrl
 * @return {boolean}
 */
function uploadField(config, field, fileUrl) {

	if (!(field in config) && config[field] === null) {
		return false;
	}
	let customField = document.getElementById('xfupload_' + config[field]);

	if (typeof customField === 'undefined') {
		return false;
	}

	let query = $.param({
		mod: 'upload',
		subaction: 'upload',
		news_id: newsIdCCDN,
		area: 'xfieldsimage',
		author: memberCCDN.name,
		user_hash: loginHashIdCCDN,
		xfname: config[field],
	});


	let dle_v = parseInt(DLEConfig.version_id);
	let url = '/engine/ajax/controller.php?';

	if (dle_v <= 12) {
		url = 'engine/ajax/upload.php?'
	}

	$.post(url + query, {
		imageurl: fileUrl.replace('https://', 'http://'),
	}).done(function (response) {
		response = JSON.parse(response);
		if (response.success) {
			let returnbox = response.returnbox;
			let returnval = response.xfvalue;
            let poster_url = returnval.split('|')[0]

			returnbox = returnbox.replace(/&lt;/g, "<");
			returnbox = returnbox.replace(/&gt;/g, ">");
			returnbox = returnbox.replace(/&amp;/g, "&");

            $('#uploadedfile_' + config[field]).html(returnbox);
			$('#xf_' + config[field]).val(returnval);
			$('#xfupload_' + config[field] + ' .qq-upload-button, #xfupload_' + config[field] + ' .qq-upload-button input').attr("disabled", "disabled");

			setData(config, 'button_download_poster_url', '/uploads/posts/' + poster_url);
			setData(config, 'button_download_poster_url_with_domain', window.location.origin + '/uploads/posts/' + poster_url);

			setTimeout(function () {
				$('#uploadfile-' + config[field]).fadeOut('slow', function () {
					$(this).remove();
				});
			}, 1000);

		} else {
			if (response.error) $('#uploadfile-' + config[field] + ' .qq-status').append('<br /><span style="color:#ff0000;">' + response.error + '</span>');
			setTimeout(function () {
				$('#uploadfile-' + config[field]).fadeOut('slow');
			}, 4000);
		}
	}).fail(function (response) {
		console.log(response);
	}).then(function (response) {
	});
}
