
//https://stackoverflow.com/a/18197341/7200161
function download(filename, text) {
	var element = document.createElement('a');
	element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
	element.setAttribute('download', filename);

	element.style.display = 'none';
	document.body.appendChild(element);

	element.click();

	document.body.removeChild(element);
}

window.directModdedPassages ??= {};

setup.editorCreate = function(domId,passageId){

	jUIPromise.then(function () {

		const Inline = Quill.import('blots/inline');
		class BoldBlot extends Inline {
			static blotName = 'bold';
			static tagName = 'strong';
		}

		Quill.register(BoldBlot);

		$('#fey-button').on('click',()=>{
			//quill.format('bold', (quill.getFormat().bold !== true));

			let text = '';
			for(const pId of Object.keys(window.directModdedPassages ?? {})){
				const existingPassage = Story.get(pId);
				const storyText = existingPassage.text.replaceAll(`&`, `&amp;`).replaceAll(`<`, `&lt;`).replaceAll(`>`, `&gt;`).replaceAll(`"`, `&quot;`).replaceAll(`'`, `&#39;`);
				//text += `:: ${pId}[${Story.get(pId).tags.join(' ')}]\n${storyText}\n`;
				const headerAttr = existingPassage.element.attributes;
				const header = `<tw-passagedata pid="${headerAttr.pid.value}" name="${headerAttr.name.value}" tags="${headerAttr.tags.value}" position="${headerAttr.position.value}" size="${headerAttr.size.value}">`;
				text += `${header}${storyText}</tw-passagedata>`
				//text += Story.get(pId).element.outerHTML.replaceAll(`&`, `&amp;`).replaceAll(`<`, `&lt;`).replaceAll(`>`, `&gt;`).replaceAll(`"`, `&quot;`).replaceAll(`'`, `&#39;`);
			}
			text += '\n.-.-.-. STORYDATA / SCRIPT .-.-.-.\n';
			download('patch.html',text);
		})

		$('#gay-button').on('click',()=>{
			Story.get(passageId).text = quill.getText();
			window.directModdedPassages[passageId] = true;
		})




		const quill = new Quill(domId);

		quill.setText(Story.get(passageId).text);

		return quill;
	});
}