# Copyright (c) 2017, Xhiveframework and Contributors
# License: GNU General Public License v3. See license.txt


import xhiveframework


def execute():
	xhiveframework.reload_doc("stock", "doctype", "item_barcode")
	if xhiveframework.get_all("Item Barcode", limit=1):
		return
	if "barcode" not in xhiveframework.db.get_table_columns("Item"):
		return

	items_barcode = xhiveframework.db.sql(
		"select name, barcode from tabItem where barcode is not null", as_dict=True
	)
	xhiveframework.reload_doc("stock", "doctype", "item")

	for item in items_barcode:
		barcode = item.barcode.strip()

		if barcode and "<" not in barcode:
			try:
				xhiveframework.get_doc(
					{
						"idx": 0,
						"doctype": "Item Barcode",
						"barcode": barcode,
						"parenttype": "Item",
						"parent": item.name,
						"parentfield": "barcodes",
					}
				).insert()
			except (xhiveframework.DuplicateEntryError, xhiveframework.UniqueValidationError):
				continue
