electronic = {}

local power = networks.power
local M = minetest.get_meta
local CYCLE_TIME = 2
local GEN_MAX = 20
local CON_MAX = 5
local SOL_PEAK = 130
local ELE1_MAX_CABLE_LENGHT = 1000

local function round(val)
	if val > 100 then
		return math.floor(val + 0.5)
	elseif val > 10 then
		return math.floor((val * 10) + 0.5) / 10
	else
		return math.floor((val * 100) + 0.5) / 100
	end
end

-------------------------------------------------------------------------------
-- Cable
-------------------------------------------------------------------------------

local Cable = tubelib2.Tube:new({
	dirs_to_check = {1,2,3,4,5,6},
	max_tube_length = ELE1_MAX_CABLE_LENGHT,
	show_infotext = false,
	tube_type = "pwr",
	primary_node_names = {"electronic:cableS", "electronic:cableA"},
	secondary_node_names = {},
  after_place_tube = function(pos, param2, tube_type, num_tubes)
		local name = minetest.get_node(pos).name
		if name == "techage:powerswitch_box" or name == "techage:powerswitch_box_on" or name == "techage:powerswitch_box_off" then
			minetest.swap_node(pos, {name = name, param2 = param2 % 32})
		elseif name == "techage:power_line" or name == "techage:power_lineS" or name == "techage:power_lineA" then
			minetest.swap_node(pos, {name = "techage:power_line"..tube_type, param2 = param2 % 32})
		elseif name == "techage:power_pole2" then
			-- nothing
		elseif not networks.hidden_name(pos) then
			minetest.swap_node(pos, {name = "electronic:cable"..tube_type, param2 = param2})
		end
		M(pos):set_int("netw_param2", param2)
	end,
})

Cable:register_on_tube_update2(function(pos, outdir, tlib2, node)
	power.update_network(pos, outdir, tlib2, node)
end)

minetest.register_node("electronic:cableS", {
  description = "Cable",
	tiles = {
		"cablerand.png",
		"cablerand.png",
		"cablerand.png",
		"cablerand.png",
		"cablemiddle.png",
		"cablemiddle.png"
	},
  after_place_node = function(pos, placer, itemstack, pointed_thing)
		if not Cable:after_place_tube(pos, placer, pointed_thing) then
			minetest.remove_node(pos)
			return true
		end
		return false
	end,
	after_dig_node = function(pos, oldnode, oldmetadata, digger)
		Cable:after_dig_tube(pos, oldnode, oldmetadata)
	end,
	drawtype = "nodebox",
	paramtype = "light",
  paramtype2 = "facedir", -- important!
  on_rotate = screwdriver.disallow, -- important!
	groups = {handy = 2, cable = 1},
	node_box = {
		type = "fixed",
		fixed = {
			{-0.185, -0.185, -0.5, 0.185, 0.185, 0.5},
		}
	}
})

minetest.register_node("electronic:cableA", {
	tiles = {
		"cablerand.png",
		"cablemiddle.png",
		"cablerand.png",
		"cablerand.png",
		"cablerand.png",
		"cablemiddle.png",
	},
  after_dig_node = function(pos, oldnode, oldmetadata, digger)
		Cable:after_dig_tube(pos, oldnode, oldmetadata)
	end,
	drawtype = "nodebox",
	paramtype = "light",
  paramtype2 = "facedir", -- important!
  on_rotate = screwdriver.disallow, -- important!
	groups = {handy = 2, cable = 1},
	node_box = {
		type = "fixed",
		fixed = {
      {-0.185, -0.5, -0.185,  0.185, 0.185,  0.185},
			{-0.185, -0.185, -0.5,  0.185, 0.185, -0.185},
		}
	},
	drop = "electronic:cableS",
})

local size = 0.185
local Boxes = {
	{{-size, -size,  size, size,  size, 0.5 }}, -- z+
	{{-size, -size, -size, 0.5,   size, size}}, -- x+
	{{-size, -size, -0.5,  size,  size, size}}, -- z-
	{{-0.5,  -size, -size, size,  size, size}}, -- x-
	{{-size, -0.5,  -size, size,  size, size}}, -- y-
	{{-size, -size, -size, size,  0.5,  size}}, -- y+
}

local names = networks.register_junction("electronic:junction", size, Boxes, Cable, {
	description = "Electronic Junction",
	tiles = {"cablemiddle.png"},
	after_place_node = function(pos, placer, itemstack, pointed_thing)
		local name = "electronic:junction"..networks.junction_type(pos, Cable)
		minetest.swap_node(pos, {name = name, param2 = 0})
		Cable:after_place_node(pos)
	end,
	-- junction needs own 'tubelib2_on_update2' to be able to call networks.junction_type
	tubelib2_on_update2 = function(pos, outdir, tlib2, node)
		if not networks.hidden_name(pos) then
			local name = "electronic:junction" .. networks.junction_type(pos, Cable)
			minetest.swap_node(pos, {name = name, param2 = 0})
		end
		power.update_network(pos, 0, tlib2, node)
	end,
	after_dig_node = function(pos, oldnode, oldmetadata, digger)
		Cable:after_dig_node(pos)
	end,
	use_texture_alpha = "clip",
	is_ground_content = false,
	groups = {crumbly = 2, cracky = 2, handy = 2, test_trowel = 1},
}, 63)

power.register_nodes(names, Cable, "junc")

-------------------------------------------------------------------------------
-- Generator
-------------------------------------------------------------------------------
-- up, down, right, left, back, front

minetest.register_node("electronic:produzent", {
	description = "Produzent",
	paramtype2 = "facedir",
  groups = {handy = 1, produzent = 1},
  tiles = {"produzent.png",
					"produzent.png",
					"produzent.png",
					"produzent.png",
					"produzent.png",
					"produzent.png^cableout.png",
	},
	after_place_node = function(pos)
		local outdir = networks.side_to_outdir(pos, "F")
		M(pos):set_int("outdir", outdir)
		Cable:after_place_node(pos, {outdir})
		M(pos):set_string("infotext", "off")
		tubelib2.init_mem(pos)
	end,
	after_dig_node = function(pos, oldnode, oldmetadata)
		local outdir = tonumber(oldmetadata.fields.outdir or 0)
		Cable:after_dig_node(pos, {outdir})
		tubelib2.del_mem(pos)
	end,
	on_timer = function(pos, elapsed)
		local outdir = M(pos):get_int("outdir")
		local mem = tubelib2.get_mem(pos)
		mem.provided = power.provide_power(pos, Cable, outdir, GEN_MAX)
		mem.load = power.get_storage_load(pos, Cable, outdir, GEN_MAX)
		M(pos):set_string("infotext", "Bereitgestellt "..round(mem.provided))
		return true
	end,
	on_rightclick = function(pos, node, clicker)
		local mem = tubelib2.get_mem(pos)
		if mem.running then
			mem.running = false
			M(pos):set_string("infotext", "off")
			minetest.get_node_timer(pos):stop()
		else
			mem.provided = mem.provided or 0
			mem.running = true
			M(pos):set_string("infotext", "Bereitgestellt "..round(mem.provided))
			minetest.get_node_timer(pos):start(CYCLE_TIME)
		end
		local outdir = M(pos):get_int("outdir")
		power.start_storage_calc(pos, Cable, outdir)
	end,
	get_generator_data = function(pos, outdir, tlib2)
		local mem = tubelib2.get_mem(pos)
		if mem.running then
			-- generator storage capa = 2 * performance
			return {level = (mem.load or 0) / GEN_MAX, perf = GEN_MAX, capa = GEN_MAX * 2}
		end
	end,
})

power.register_nodes({"electronic:produzent"}, Cable, "gen", {"F"})


--[[minetest.register_node("electronic:cable", {
  groups = {snappy = 1, leiter = 1},
  tiles = {"cable.png"},
  desctiption = "Kabel",
  after_place_node = function(pos, placer, itemstack, pointed_thing)
    local meta = minetest.get_meta(pos)
    meta:set_float("watt-tick", 0)
  end
})]]

-------------------------------------------------------------------------------
-- Solar
-------------------------------------------------------------------------------
-- up, down, right, left, back, front

minetest.register_node("electronic:solar", {
	description = "Solar",
	paramtype2 = "facedir",
  groups = {handy = 1, produzent = 1},
  tiles = {"solar_top.png",
					"solar_side.png^cableout.png",
					"solar_side.png",
					"solar_side.png",
					"solar_side.png",
					"solar_side.png",
	},
	drawtype = "nodebox",
	node_box = {
		type = "fixed",
		fixed = {
			{-0.5, 4/16, -0.5, 0.5, 6/16, 0.5},
			{-2/16, -0.5, -2/16, 2/16, 4/16, 2/16 }
		}
	},
	after_place_node = function(pos)
		local outdir = networks.side_to_outdir(pos, "D")
		M(pos):set_int("outdir", outdir)
		Cable:after_place_node(pos, {outdir})
		M(pos):set_string("infotext", "off")
		tubelib2.init_mem(pos)
	end,
	after_dig_node = function(pos, oldnode, oldmetadata)
		local outdir = tonumber(oldmetadata.fields.outdir or 0)
		Cable:after_dig_node(pos, {outdir})
		tubelib2.del_mem(pos)
	end,
	on_timer = function(pos, elapsed)
		local outdir = M(pos):get_int("outdir")
		local mem = tubelib2.get_mem(pos)
		local time = minetest.get_timeofday()*24000
		if (time >= 5000 and time < 6000) or (time >= 18000 and time < 1900) then
			mem.provided = power.provide_power(pos, Cable, outdir, SOL_PEAK/30)
			mem.load = power.get_storage_load(pos, Cable, outdir, SOL_PEAK/30)
		elseif (time >= 6000 and time < 8000) or (time >= 15000 and time < 18000) then
			mem.provided = power.provide_power(pos, Cable, outdir, SOL_PEAK/10)
			mem.load = power.get_storage_load(pos, Cable, outdir, SOL_PEAK/10)
		elseif (time >= 8000 and time < 10000) or (time >= 12000 and time < 15000) then
			mem.provided = power.provide_power(pos, Cable, outdir, SOL_PEAK/4)
			mem.load = power.get_storage_load(pos, Cable, outdir, SOL_PEAK/4)
		elseif time >= 10000 and time < 12000 then
			mem.provided = power.provide_power(pos, Cable, outdir, SOL_PEAK)
			mem.load = power.get_storage_load(pos, Cable, outdir, SOL_PEAK)
		else
			mem.running = 0
			M(pos):set_string("infotext", "Zu wenig Licht!")
		end
		M(pos):set_string("infotext", "Bereitgestellt "..round(mem.provided))
		return true
	end,
	on_rightclick = function(pos, node, clicker)
		local mem = tubelib2.get_mem(pos)
		if mem.running then
			mem.running = false
			M(pos):set_string("infotext", "off")
			minetest.get_node_timer(pos):stop()
		else
			mem.provided = mem.provided or 0
			mem.running = true
			M(pos):set_string("infotext", "Bereitgestellt "..round(mem.provided))
			minetest.get_node_timer(pos):start(CYCLE_TIME)
		end
		local outdir = M(pos):get_int("outdir")
		power.start_storage_calc(pos, Cable, outdir)
	end,
	get_generator_data = function(pos, outdir, tlib2)
		local mem = tubelib2.get_mem(pos)
		if mem.running then
			-- generator storage capa = 2 * performance
			return {level = (mem.load or 0) / GEN_MAX, perf = GEN_MAX, capa = GEN_MAX * 2}
		end
	end,
})

power.register_nodes({"electronic:solar"}, Cable, "gen", {"D"})

-------------------------------------------------------------------------------
-- Konsument
-------------------------------------------------------------------------------

local function swap_node(pos, name)
	local node = tubelib2.get_node_lvm(pos)
	if node.name == name then
		return
	end
	node.name = name
	minetest.swap_node(pos, node)
end

local function turn_on(pos)
	swap_node(pos, "electronic:konsument_light")
	M(pos):set_string("infotext", "on")
	local mem = tubelib2.get_mem(pos)
	mem.running = true
	minetest.get_node_timer(pos):start(CYCLE_TIME)
end

local function turn_off(pos)
	swap_node(pos, "electronic:konsument")
	M(pos):set_string("infotext", "off")
	local mem = tubelib2.get_mem(pos)
	mem.running = false
	minetest.get_node_timer(pos):stop()
end

local function on_rightclick(pos, node, clicker)
	local mem = tubelib2.get_mem(pos)
	if not mem.running and power.power_available(pos, Cable) then
		turn_on(pos)
	else
		turn_off(pos)
	end
end

local function after_place_node(pos)
	M(pos):set_string("infotext", "off")
	Cable:after_place_node(pos)
	tubelib2.init_mem(pos)
end

local function after_dig_node(pos, oldnode)
	Cable:after_dig_node(pos)
	tubelib2.del_mem(pos)
end

minetest.register_node("electronic:konsument", {
  groups = {handy = 1, konsument = 1},
  tiles = {"konsument.png"},
  description = "Konsument",
	on_timer = function(pos, elapsed)
		local consumed = power.consume_power(pos, Cable, nil, CON_MAX)
		if consumed == CON_MAX then
			swap_node(pos, "electronic:konsument_light")
			M(pos):set_string("infotext", "on")
		end
		return true
	end,
	on_rightclick = on_rightclick,
	after_place_node = after_place_node,
	after_dig_node = after_dig_node,
	paramtype2 = "facedir",
})

minetest.register_node("electronic:konsument_light", {
  groups = {handy = 1, konsument = 1},
  tiles = {"konsument.png"},
  light_source = 14,
	on_timer = function(pos, elapsed)
		print(Cable)
		local consumed = power.consume_power(pos, Cable, nil, CON_MAX)
		if consumed < CON_MAX then
			swap_node(pos, "electronic:konsument")
			M(pos):set_string("infotext", "no power")
		end
		return true
	end,
	on_rightclick = on_rightclick,
	after_place_node = after_place_node,
	after_dig_node = after_dig_node,
	drop = "electronic:konsument",
})

power.register_nodes({"electronic:konsument", "electronic:konsument_light"}, Cable, "con")


-------------------------------------------------------------------------------
-- Function and variables
-------------------------------------------------------------------------------

electronic.ElectricCable = Cable
electronic.ELE1_MAX_CABLE_LENGTH = ELE1_MAX_CABLE_LENGHT

--[[minetest.register_abm{
  label = "electric",
	nodenames = {"electronic:cable"},
	interval = 0.05,
	chance = 1,
	action = function(pos)
    done = done + 1
    minetest.chat_send_all(done)
    local highest = 0
    local tempos = {x=pos.x+1,y=pos.y,z=pos.z}
    if minetest.get_meta(tempos):get_float("watt-tick") > highest and (minetest.get_item_group(minetest.get_node(tempos), "konsument") >= 1 or minetest.get_item_group(minetest.get_node(tempos), "leiter") >= 1) then
      highest = minetest.get_meta(tempos):get_float("watt-tick")
    end
    if minetest.get_meta({x=pos.x-1,y=pos.y,z=pos.z}):get_float("watt-tick") > highest and (minetest.get_item_group(minetest.get_node({x=pos.x-1,y=pos.y,z=pos.z}), "konsument") >= 1 or minetest.get_item_group(minetest.get_node({x=pos.x-1,y=pos.y,z=pos.z}), "leiter") >= 1) then
      highest = minetest.get_meta({x=pos.x-1,y=pos.y,z=pos.z}):get_float("watt-tick")
    end
    if minetest.get_meta({x=pos.x,y=pos.y+1,z=pos.z}):get_float("watt-tick") > highest and (minetest.get_item_group(minetest.get_node({x=pos.x,y=pos.y+1,z=pos.z}), "konsument") >= 1 or minetest.get_item_group(minetest.get_node({x=pos.x,y=pos.y+1,z=pos.z}), "leiter") >= 1) then
      highest = minetest.get_meta({x=pos.x,y=pos.y+1,z=pos.z}):get_float("watt-tick")
    end
    if minetest.get_meta({x=pos.x,y=pos.y-1,z=pos.z}):get_float("watt-tick") > highest and (minetest.get_item_group(minetest.get_node({x=pos.x,y=pos.y-1,z=pos.z}), "konsument") >= 1 or minetest.get_item_group(minetest.get_node({x=pos.x,y=pos.y-1,z=pos.z}), "leiter") >= 1) then
      highest = minetest.get_meta({x=pos.x,y=pos.y-1,z=pos.z}):get_float("watt-tick")
    end
    if minetest.get_meta({x=pos.x,y=pos.y,z=pos.z+1}):get_float("watt-tick") > highest and (minetest.get_item_group(minetest.get_node({x=pos.x,y=pos.y,z=pos.z+1}), "konsument") >= 1 or minetest.get_item_group(minetest.get_node({x=pos.x,y=pos.y,z=pos.z+1}), "leiter") >= 1) then
      highest = minetest.get_meta({x=pos.x,y=pos.y,z=pos.z+1}):get_float("watt-tick")
    end
    if minetest.get_meta({x=pos.x,y=pos.y,z=pos.z-1}):get_float("watt-tick") > highest and (minetest.get_item_group(minetest.get_node({x=pos.x,y=pos.y,z=pos.z-1}), "konsument") >= 1 or minetest.get_item_group(minetest.get_node({x=pos.x,y=pos.y,z=pos.z-1}), "leiter") >= 1) then
      highest = minetest.get_meta({x=pos.x,y=pos.y,z=pos.z-1}):get_float("watt-tick")
    end
    minetest.get_meta(pos):set_float("watt-tick", highest)
    --print(highest)
	end,
}]]
