# Copyright (c) 2015, InfluxFramework LLC
# License: MIT. See LICENSE

# License: MIT. See LICENSE

import influxframework
from influxframework import _
from influxframework.model.document import Document


class Blogger(Document):
	def validate(self):
		if self.user and not influxframework.db.exists("User", self.user):
			# for data import
			influxframework.get_doc(
				{"doctype": "User", "email": self.user, "first_name": self.user.split("@")[0]}
			).insert()

	def on_update(self):
		"if user is set, then update all older blogs"

		from influxframework.website.doctype.blog_post.blog_post import clear_blog_cache

		clear_blog_cache()

		if self.user:
			for blog in influxframework.db.sql_list(
				"""select name from `tabBlog Post` where owner=%s
				and ifnull(blogger,'')=''""",
				self.user,
			):
				b = influxframework.get_doc("Blog Post", blog)
				b.blogger = self.name
				b.save()

			influxframework.permissions.add_user_permission("Blogger", self.name, self.user)
