// Copyright (c) 2015, JINGROW and Contributors
// MIT License. See license.txt

jingrow.provide("jingrow.views.formview");

jingrow.views.FormFactory = class FormFactory extends jingrow.views.Factory {
	make(route) {
		var pagetype = route[1],
			pagetype_layout = jingrow.router.pagetype_layout || pagetype;

		if (!jingrow.views.formview[pagetype_layout]) {
			jingrow.model.with_pagetype(pagetype, () => {
				this.page = jingrow.container.add_page(pagetype_layout);
				jingrow.views.formview[pagetype_layout] = this.page;
				this.make_and_show(pagetype, route);
			});
		} else {
			this.show_pg(route);
		}

		this.setup_events();
	}

	make_and_show(pagetype, route) {
		if (jingrow.router.pagetype_layout) {
			jingrow.model.with_pg("PageType Layout", jingrow.router.pagetype_layout, () => {
				this.make_form(pagetype);
				this.show_pg(route);
			});
		} else {
			this.make_form(pagetype);
			this.show_pg(route);
		}
	}

	make_form(pagetype) {
		this.page.frm = new jingrow.ui.form.Form(
			pagetype,
			this.page,
			true,
			jingrow.router.pagetype_layout
		);
	}

	setup_events() {
		if (!this.initialized) {
			$(document).on("page-change", function () {
				jingrow.ui.form.close_grid_form();
			});
		}
		this.initialized = true;
	}

	show_pg(route) {
		var pagetype = route[1],
			pagetype_layout = jingrow.router.pagetype_layout || pagetype,
			name = route.slice(2).join("/");

		if (jingrow.model.new_names[name]) {
			// document has been renamed, reroute
			name = jingrow.model.new_names[name];
			jingrow.set_route("Form", pagetype_layout, name);
			return;
		}

		const pg = jingrow.get_pg(pagetype, name);
		if (
			pg &&
			jingrow.model.get_pageinfo(pagetype, name) &&
			(pg.__islocal || jingrow.model.is_fresh(pg))
		) {
			// is document available and recent?
			this.render(pagetype_layout, name);
		} else {
			this.fetch_and_render(pagetype, name, pagetype_layout);
		}
	}

	fetch_and_render(pagetype, name, pagetype_layout) {
		jingrow.model.with_pg(pagetype, name, (name, r) => {
			if (r && r["403"]) return; // not permitted

			if (!(locals[pagetype] && locals[pagetype][name])) {
				if (name && name.substr(0, 3) === "new") {
					this.render_new_pg(pagetype, name, pagetype_layout);
				} else {
					jingrow.show_not_found();
				}
				return;
			}
			this.render(pagetype_layout, name);
		});
	}

	render_new_pg(pagetype, name, pagetype_layout) {
		const new_name = jingrow.model.make_new_pg_and_get_name(pagetype, true);
		if (new_name === name) {
			this.render(pagetype_layout, name);
		} else {
			jingrow.route_flags.replace_route = true;
			jingrow.set_route("Form", pagetype_layout, new_name);
		}
	}

	render(pagetype_layout, name) {
		jingrow.container.change_to(pagetype_layout);
		jingrow.views.formview[pagetype_layout].frm.refresh(name);
	}
};
