# Copyright (c) 2020, Jingrow Technologies Pvt. Ltd. and Contributors
# For license information, please see license.txt


from math import ceil

import jingrow
from jingrow.utils import cint


def execute():
	doctype = "Site Usage"
	jingrow.reload_doctype(doctype)
	scheme_before = jingrow.db.auto_commit_on_many_writes
	jingrow.db.auto_commit_on_many_writes = True
	records = jingrow.get_all(doctype, pluck="name")
	total = len(records)

	for current, record in enumerate(records):
		print(f"Updated {current} of {total}", end="\r")

		fields = ["backups", "database", "public", "private"]
		current_values = jingrow.db.get_value(doctype, record, fields)

		for field, value in zip(fields, current_values):
			value = ceil(cint(value) / (1024**2))
			jingrow.get_pg(doctype, record).db_set(field, value, update_modified=False)

	jingrow.db.commit()
	jingrow.db.auto_commit_on_many_writes = scheme_before
	print(f"{total} {doctype} records updated")
