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


import influxframework


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

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

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

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