import { ScopeMessageList } from 'Common/Enums';
import { doc, createElement, Settings } from 'Common/Globals';
import { pString, pInt } from 'Common/Utils';
import { moveAction } from 'Common/UtilsUser';
import { getFolderFromHashMap, getFolderInboxName } from 'Common/Cache';
import { i18n, initOnStartOrLangChange } from 'Common/Translator';

import { AppUserStore } from 'Stores/User/App';
import { AccountUserStore } from 'Stores/User/Account';
import { FolderUserStore } from 'Stores/User/Folder';
import { MessagelistUserStore } from 'Stores/User/Messagelist';

import { SystemDropDownUserView } from 'View/User/SystemDropDown';
import { MailFolderList } from 'View/User/MailBox/FolderList';
import { MailMessageList } from 'View/User/MailBox/MessageList';
import { MailMessageView } from 'View/User/MailBox/MessageView';

import { AbstractScreen } from 'Knoin/AbstractScreen';

import { MessageModel } from 'Model/Message';
import { populateMessageBody } from 'Common/UtilsUser';

export class MailBoxUserScreen extends AbstractScreen {
	constructor() {
		var styleSheet = createElement('style');
		doc.head.appendChild(styleSheet);
		initOnStartOrLangChange(() =>
			styleSheet.innerText = '.subjectParent:empty::after,.subjectParent .subject:empty::after'
			+'{content:"'+i18n('MESSAGE/EMPTY_SUBJECT_TEXT')+'"}'
		);
		super('mailbox', [
			SystemDropDownUserView,
			MailFolderList,
			MailMessageList,
			MailMessageView
		]);
	}

	/**
	 * @returns {void}
	 */
	updateWindowTitle() {
		const count = Settings.app('listPermanentFiltered') ? 0 : FolderUserStore.foldersInboxUnreadCount(),
			email = AccountUserStore.email();

		rl.setTitle(
			(email
				? '' + (0 < count ? '(' + count + ') ' : ' ') + email + ' - '
				: ''
			) + i18n('TITLES/MAILBOX')
		);
	}

	/**
	 * @returns {void}
	 */
	onShow() {
		this.updateWindowTitle();
		AppUserStore.focusedState('none');
		AppUserStore.focusedState(ScopeMessageList);
	}

	/**
	 * @param {string} folderHash
	 * @param {number} page
	 * @param {string} search
	 * @returns {void}
	 */
	onRoute(folderHash, page, search, messageUid) {
		// Only works when FolderUserStore.folderList() is loaded
		const folder = getFolderFromHashMap(folderHash.replace(/~([\d]+)$/, ''));
		if (folder) {
			FolderUserStore.currentFolder(folder);
			MessagelistUserStore.page(1 > page ? 1 : page);
			MessagelistUserStore.listSearch(search);
			if (messageUid) {
				let message = new MessageModel;
				message.folder = folderHash;
				message.uid = messageUid;
				populateMessageBody(message);
			} else {
				let threadUid = folderHash.replace(/^.+~(\d+)$/, '$1');
				MessagelistUserStore.threadUid((folderHash === threadUid) ? 0 : pInt(threadUid));
			}
			MessagelistUserStore.reload();
		}
	}

	/**
	 * @returns {void}
	 */
	onStart() {
		super.onStart();

		addEventListener('mailbox.inbox-unread-count', e => {
			FolderUserStore.foldersInboxUnreadCount(e.detail);
/*			// Disabled in SystemDropDown.html
			const email = AccountUserStore.email();
			AccountUserStore.forEach(item =>
				email === item?.email && item?.count(e.detail)
			);
*/
			this.updateWindowTitle();
		});
	}

	/**
	 * @returns {void}
	 */
	onBuild() {
		doc.addEventListener('click', event =>
			event.target.closest('#rl-right') && moveAction(false)
		);
	}

	/**
	 * Parse link as generated by mailBox()
	 * @returns {Array}
	 */
	routes() {
		const
			folder = (request, vals) => request ? pString(vals[0]) : getFolderInboxName(),
			fNormS = (request, vals) => [folder(request, vals), request ? pInt(vals[1]) : 1, decodeURI(pString(vals[2]))];

		return [
			// Folder: INBOX | INBOX.sub | Sent | fullNameHash
			[/^([^/]*)$/, { normalize_: fNormS }],
			// Search: {folder}/{string}
			[/^([a-zA-Z0-9.~_-]+)\/(.+)\/?$/, { normalize_: (request, vals) =>
				[folder(request, vals), 1, decodeURI(pString(vals[1]))]
			}],
			// Message: {folder}/m{uid}(/{search})?
			[/^([a-zA-Z0-9.~_-]+)\/m([1-9][0-9]*)(?:\/(.+))?$/, { normalize_: (request, vals) =>
				[folder(request, vals), 1, pString(vals[2]), pString(vals[1])]
			}],
			// Page: {folder}/p{int}(/{search})?
			[/^([a-zA-Z0-9.~_-]+)\/p([1-9][0-9]*)(?:\/(.+))?$/, { normalize_: fNormS }]
		];
	}
}
