"""Routes for edit/properties."""
import os, json, pandas, security, surveyparser, shutil, utils
from bottle import Bottle, route, view, redirect, post, request

properties = Bottle()

@properties.route("/surveys/<name>/properties")
@view("properties")
@security.require_admin
def edit_properties(name):
	"""Presents user with form to edit survey's properties or enter them for
	the first time if uploading."""
	survey, properties = surveyparser.get_survey(name)

	base = os.path.join("db", "surveys")
	os.makedirs(base, exist_ok=True) # Make sure surveys/ or create it otherwise
	surveys = next(os.walk(base))[1] # List dirs only

	return dict(
		survey_name = name,
		survey = survey,
		metadata = surveyparser.get_metadata(name),
		properties = properties,
		uploading = request.query.get("uploading"),
		surveys = surveys,
	)

@properties.post("/surveys/<name>/properties")
@view("properties")
@security.require_admin
def edit_properties(name):
	"""Apply and write changes."""
	# Parse survey given touchpoint columns (part of metadata) and deleted
	# columns (will be deleted in raw) and dump it
	new_survey, new_metadata = surveyparser.parse_file(
		os.path.join("db", "surveys", name, "raw.csv"),
		request.forms.getall("touchpoint-columns"),
		request.forms.getall("deleted-columns")
	)
	base = os.path.join("db", "surveys", name)
	surveyparser.write(new_survey, base, new_metadata)

	# Populate new properties dict and dump it
	new_properties = {
		"public": request.forms.get("public"),
		"anon-matches": max(0, int(request.forms.get("anon-matches"))),
		"compare-with": request.forms.get("compare-with"),
		"guests": 0,
		"notes": request.forms.get("notes"),
		"filterable-columns": request.forms.getall("filterable-columns"),
		"touchpoint-columns": request.forms.getall("touchpoint-columns"),
	}
	utils.safejsondump(new_properties, os.path.join(base, "properties.json"))

	# If public state changed for good change public.json to reflect it
	public_path = os.path.join("db","surveys", "public.json")
	public = utils.safejsonload(public_path, fallback=[])
	if bool(request.forms.get("public")) != (name in public):
		if name in public:
			public.remove(name)
		else:
			public.append(name)
		utils.safejsondump(public, public_path)

	# Go to next step if user came from /upload
	if request.query.get("uploading"):
		redirect("/surveys/" + name + "/readings?uploading=1")

	redirect("/surveys")
