import DataUtils, {
	REQUEST_TYPE_POST,
	CONTENT_TYPE_JSON
} from '../../../../../brain//tools/utilities/DataUtils';
import DateUtils from '../../../../../brain/tools/utilities/DateUtils';
import * as DataEvent from '../../../../../brain/tools/events/DataEvent';
export default class SettingsActions {
	//--------------------------
	// constructor
	//--------------------------
	constructor() {
		this.dataUtils = new DataUtils();
		this.dateUtils = new DateUtils();
	}
	//--------------------------
	// methods
	//--------------------------
	save() {
		let self = this;
		let handle = document.getElementById('settings-handle').value;
		let email = document.getElementById('settings-email').value;
		let url = document.getElementById('settings-url').value;
		let title = document.getElementById('settings-title').value;
		let desc = document.getElementById('settings-desc').innerHTML;
		let privacy = document.getElementById('privacy-toggle').getAttribute('data-private');
		let background = document.getElementById('background').src;
		let selected = '';
		let selects = document.querySelectorAll('.theme-select');
		let smtpDomain = document.getElementById('smtp-domain').value;
		let smtpEmail = document.getElementById('smtp-email').value;
		let smtpPass = document.getElementById('smtp-pass').value;
		let mgDomain = document.getElementById('mg-domain').value;
		let mgKey = document.getElementById('mg-key').value;
		let mailActive = '';
		let mailOptions = document.querySelectorAll('.mail-option');
		var i, count;
		for (i = 0, count = selects.length; i < count; i++) {
			if (selects[i].getAttribute('data-enabled') == 'true') selected = selects[i].id;
		}

		for (i = 0, count = mailOptions.length; i < count; i++) {
			if (mailOptions[i].getAttribute('data-enabled') == 'true')
				mailActive = mailOptions[i].id;
		}
		let settingsData = {
			handle: handle,
			email: email,
			url: url,
			title: title,
			descriptions: desc,
			background: background,
			private: privacy,
			theme: selected,
			mailSettings: {
				activeProtocol: mailActive,
				smtp: {
					domain: smtpDomain,
					email: smtpEmail,
					password: smtpPass
				},
				mailgun: {
					domain: mgDomain,
					key: mgKey
				}
			}
		};
		return new Promise(function(resolve, reject) {
			self.dataUtils
				.request(
					'/api/settings/sync',
					DataEvent.SETTINGS_UPDATED,
					REQUEST_TYPE_POST,
					CONTENT_TYPE_JSON,
					settingsData
				)
				.then(response => {
					//console.log("RESPONSE", response)
					resolve(response);
				})
				.catch(err => {
					reject(err);
				});
		});
	}
	//--------------------------
	// event handlers
	//--------------------------
}
