local bg_screen = --32px resolution
   'formspec_version[3]'..
   'size[6,7]'..
   'bgcolor[;neither]'

function sss_core.power_substation(pos)
   local meta = minetest.get_meta(pos)
   local status = meta:get_int('status')
   local formspec =
      bg_screen..
      'background[-1,-1;8,9;sss_core_power_substation_'..status..'.png]'..
      'style_type[image_button;border=false;bgimg=blank.png]'..
      'image_button[1,.75;4,1.25;;switch;]'
   return formspec
end

minetest.register_on_player_receive_fields(function(player, formname, fields)
   local name = player:get_player_name()
   if formname == 'sss_core:power_substation' then
      if fields.switch then
         local pos = sss_core.player_config[name]
         local meta = minetest.get_meta(pos)
         local status = meta:get_int('status')
         local power_level = sss_core.savedata.power_level
         if power_level == 0 then
            if status == 0 then -- do opposite as the status hasn't flipped yet.
               sss_core.savedata.power_level = 3
               sss_core.savedata.power_to_fail = 'true'
               meta:set_int('status', 1)
               minetest.sound_play('power_on', {to_player = name})
               minetest.chat_send_all('Power systems back online.')
               minetest.after(180, function()
                  minetest.sound_play('power_critical', {to_player = name})
                  minetest.chat_send_all('Power systems critical.')
               end)
               minetest.after(240, function()
                  sss_core.savedata.power_level = 1
                  minetest.sound_play('power_off', {to_player = name})
                  sss_core.savedata.notifications = 'Power Transformers offline!'
                  minetest.chat_send_all('Power systems offline.')
               end)
            end
         end
         minetest.show_formspec(name, 'sss_core:power_substation', sss_core.power_substation(pos))
      end
   end
end)
