engine = engine or {}

function engine.load(args)

  print(inspect(args))
  if LOVE then 
    love._setGammaCorrect(true)
  end

  gfx.setDefaultFilter( "nearest", "nearest" )

  SAVE_DIR        = lfs.getSaveDirectory() .. "/"
  ENGINE_DIR      = lfs.getSource() .. "/"

  init()

  if args and args[1] then 
    local file = args[1]
    local base = basename(file)
    LOADED_FILE = file
    LOADED_NAME = base:gsub(".project","")
    LOADED_PATH = file:gsub(base,"")

    config.projects[LOADED_NAME]={
      dir = LOADED_PATH,
      path = LOADED_FILE,
      name = LOADED_NAME,
      modtime=os.time()
    }
    mkdir("projects")

    loadProject(LOADED_NAME,false,true)
    return 
  end

  print("check projects")
  if config and config.currentProject then 
    print("Is there a current project?") 
    if config.projects[config.currentProject] then
      print("Seems so") 
      if (file_exists("config.sav") or (not lfs.isFused())) and config.autoload then 
        print("...lets load it")
        loadProject(config.currentProject)
      end
    else 
      config.currentProject=nil
      print("NIL BROJEC")
    end
  else
    print("NO BROJEC")
  end
end

-- function love.errorhandler(msg)
--  msg = tostring(msg)
--  error_printer(msg, 2)
--  return
-- end


function loadProject(project,new,project)
  
  --if config.currentProject == project then return end
  local filename = (config.projects[project].dir or "").."/"..config.projects[project].name..".project"

  local check = (filename.."/.config"):gsub("//","/")
  print("check "..check)
  ZIP_MODE = not exists(check)

  print("ZIP_MODE "..tostring(ZIP_MODE))

  if not project and not new then 
    if  not exists(filename) then 
      print("No proj")
      config.currentProject = nil
      config.projects[project]=nil
      saveConfig()
      return 
    end
  end

  STRING=""
  if project or not new then 
    if ZIP_MODE then
      local dest = q(SAVE_DIR.."projects/"..tostring(config.projects[project].name))
      os.execute(os.rm().." "..dest)
      STRING="unzip -o -q "..q(filename).." -d "..dest.." && chmod -R 0777 "..dest
      print("exec",STRING)
      os.execute(STRING)
    end
  end

  config.currentProject = project
  CURRENT_PROJECT = project

  if game.state=="Edit" then 
    saveConfig()
    love.event.quit("restart")
  else 
    LINK_DIR        = "/projects/"..CURRENT_PROJECT.."/"
    GAME_DIR        = config.projects[CURRENT_PROJECT].path.."/"
    PROJ_DIR        = ZIP_MODE and SAVE_DIR..LINK_DIR or GAME_DIR
    lfs.write("gay.txt",STRING)
   
    loader:preLoad()
    -- local chunk = assert(lfs.load("source/libs/polywell/config/init.lua"))
    -- chunk()
    -- polywell.fs = polywell.fs or fs_for(GAME_DIR)
  end
end

function exitProject()
  CURRENT_PROJECT=nil
  RESTARTING = true
  saveConfig()
  if LOVE then 
    love.event.quit("restart")
  end
end
-----------------------------------------------------------
-- QUIT
-----------------------------------------------------------
function engine.quit()
  if animationPanel and animationPanel.newImage and animationPanel.instance then
    editor.deleteImage(animationPanel.instance.key)
  end
  saveConfig()
  return
end

-----------------------------------------------------------
-- THE MASTER LOOP 
-----------------------------------------------------------
function engine.update(dt)
  if _stop then return end

  main_dt = dt
  time = time + dt
  ltimer.fourstep = (ltimer.fourstep and ltimer.fourstep<3) and ltimer.fourstep+1 or 1
  mouse.time    = mouse.time  + 1
  
  if CURRENT_PROJECT then 
    game.update(dt)
  else 
    selectProject()
  end
  
  gfx.reset()

end

-----------------------------------------------------------
-- DRAW EVERYTHING
-----------------------------------------------------------
function engine.draw()
  if _stop then return end
  if RESTARTING then return end

  if CURRENT_PROJECT then 
    game.draw()
  else 
    drawProjects()
  end
  
end

-----------------------------------------------------------
-- RESIZE
-----------------------------------------------------------
function engine.resize(w,h)
  editor.resized=2
  keyTime = 30
  game.aspectRatio = gfx.getWidth()/gfx.getHeight()
  resizingWindow=false
  if animationPanel then animationPanel.hideSpeed=1 end
  setDimensions()
  setCanvases()
  config.window  = {size = {width=w, height=h}}
  sidebar.x = sidebar.visible and sidebar.x or screenWidth
  saveConfig()
end

-----------------------------------------------------------
-- DROP FILE
-----------------------------------------------------------
function engine.filedropped( file )
  if editingLevel then 
    fileDropped = true 
    droppedFile = file
    editor.dropFile(file)
  else
    if not CURRENT_PROJECT then 
      local dir = file:getFilename()
      local name = basename(dir)
      if dir:sub(dir:len()-4,-1)==".project" then 
        print(name:sub(1,-6))
        local noext = dir:sub(1,-6)
        config.projects[name:sub(1,-6)]={
          name=name:sub(1,-6),
          dir = dir:gsub(name,""),
          path=dir,
          modtime=os.time()
        }
        print("1: "..dir)
        print("2: "..SAVE_DIR.."projects")
        os_link(dir,SAVE_DIR.."projects")
        os.rename(SAVE_DIR.."projects/"..name,SAVE_DIR.."projects/"..name:sub(1,-6))
        splashScreen.refresh = true
        saveConfig()
      else
        config.defaultProjectLocation = dir
      end
    end
  end
end

function engine.directorydropped( dir )
  if not CURRENT_PROJECT then 
    local name = basename(dir)
    if dir:sub(dir:len()-4,-1)==".project" then 
      print(name:sub(1,-6))
      local noext = dir:sub(1,-6)
      config.projects[name:sub(1,-6)]={
        name=name:sub(1,-6),
        dir = dir:gsub(name,""),
        path=dir,
        modtime=os.time()
      }
      print("1: "..dir)
      print("2: "..SAVE_DIR.."projects")
      os_link(dir,SAVE_DIR.."projects")
      os.rename(SAVE_DIR.."projects/"..name,SAVE_DIR.."projects/"..name:sub(1,-6))
      splashScreen.refresh = true
      saveConfig()
    else
      config.defaultProjectLocation = dir
    end
  end
end

-----------------------------------------------------------
function toggleDeveloper()
  if (game.state == "Load" or game.state == "Menu") and keypressed("=") then 
    --developer=not developer
  end
end

function reloadSource()
  if game.state ~= "Load" and developer then 
    requireSources(true)
    if game.state=="Edit" then 
      imageLoader:checkImages(LINK_DIR.."images","images/")
    end
  end
end

function engine.focus( focus )
  windowFocused=focus
  if not focus then 
    lmouse.setVisible(true)  
  else
    requireSources(true)
    if game.state=="Edit" then 
      if editingLevel then 
        if editor.debug.rebuild_on_focus then 
          scene.time=-1
        end
      end
      imageLoader:checkImages(LINK_DIR.."images","images/")
    end
  end
end