--Architecture pc
EarthEngine={l=800,
             h=600,
			 screen=1,
			 type="pc"}
			 
function EarthEngine.init()
-- Set the game title name here
    luaplayer.open("Earth")

local currentdir = System.currentDirectory()




-- Reset the game main directory
System.currentDirectory(currentdir)
end

function EarthEngine.quit()
luaplayer.close()
end

package.cpath = "./dll/?.so;./dll/?.dll;./dll/?.dylib;"
require("sdl")
require("lfs");

define_width = 480
define_height = 272
define_bpp = 32

  luaplayer = {
    screen_width = define_width,
    screen_height = define_height,
    screen_bpp = define_bpp,
    keyboard_delay= 25,
    keyboard_repeat_delay= 5, -- default :500
    keyboard_repeat_interval= 5,-- default : 100
    open = function (name)
        name = name or "Lua SDL"
        if SDL.SDL_Init(SDL.SDL_INIT_EVERYTHING) < 0 then
            error("Couldn't initialize SDL: ", SDL.SDL_GetError())
        end
        SDL.SDL_WM_SetCaption(name, name)
        local videoflags = SDL.Or(SDL.SDL_SWSURFACE, SDL.SDL_ANYFORMAT,SDL.SDL_DOUBLEBUF)
        video = SDL.SDL_SetVideoMode(luaplayer.screen_width, luaplayer.screen_height, luaplayer.screen_bpp, videoflags)
        if not video then
            error("Couldn't set video mode: ", SDL.SDL_GetError())
        end
        SDL.SDL_ShowCursor(1)
        if not MiniFont_New then
            MiniFont_New = loadfile("./arch/lib/minifont.lua")
        end
        MiniFont = MiniFont_New()
        MiniFont:SetSurface(video)
        MiniFont:SetWindow(0, 0, luaplayer.screen_width, luaplayer.screen_height)
        MiniFont:Clear()
        if SDL.Mix_OpenAudio(22050, SDL.MIX_DEFAULT_FORMAT, 2, 1024) ~= 0 then
            MiniFont:Print("Couldn't open mixer: "..SDL.Mix_GetError().."\n")
          end
          if SDL.SDL_EnableKeyRepeat(luaplayer.keyboard_repeat_delay, luaplayer.keyboard_repeat_interval) ~= 0 then
            MiniFont:Print("Couldn't set EnableKeyRepeat: "..SDL.SDL_GetError().."\n")
          end
        end,
    close = function ()
        SDL.Mix_CloseAudio()
        SDL.SDL_Quit()
		os.exit()
    end
  }

  Font = {}
  function Font.load(filename) return MiniFont end
  function Font.createMonoSpaced() return MiniFont end
  function Font.createProportional() return MiniFont end
  function Font:setCharSize(width, height, dpiX, dpiY) return MiniFont end
  function Font:setPixelSizes(width, height) return MiniFont end
  function Font:getTextSize(string) return 0,0 end

  -- Color
  Color = {
    new = function (r,g,b) return SDL.SDL_MapRGB(video.format, r, g, b) end
  }
  imagesdl={}
  function imagesdl.new() 
      return a_image
  end
  ----------------------------------
  a_img={
                surf=nil,
                blit = function (x, y, img, sourcex, sourcey, width, height)
                    local s
                    local d = SDL.SDL_Rect_local()
                    d.x, d.y = x, y
                    if ox and oy and ow and oh then
                      s = SDL.SDL_Rect_local()
                      s.x, s.y, s.w, s.h = sourcex, sourcey, width, height
                    else
                      s = nil
                    end
                    SDL.SDL_BlitSurface(img, s, surf, d)
                end,
                clear = function (color)
                    SDL.SDL_FillRect(surf, nil, color or 0)
                end,
                fontPrint = function (font, x, y, txt, color)
                print("not sure 2")
                    --MiniFont:SetWindow(x, y, luaplayer.screen_width-x, luaplayer.screen_height-y) 
                    MiniFont:Print(txt)
                print("not sure 2")
                end,
                width = function () return surf.w end,
                height = function () return surf.h end,
	            fillRect= function(x, y, width, height, color)
                       local c = color or 0
                       local rect = SDL.SDL_Rect_local()
                       rect.x, rect.y = x, y
                       rect.w, rect.h = width, height
                       SDL.SDL_FillRect(surf, rect, c)
                end,
                pixel= function(x, y)
                      SDL.SDL_LockSurface(video)
                     local c = SDL.SDL_GetPixel(surf,x,y)
                     SDL.SDL_UnlockSurface(surf)
                     return {
                         colors = function ()
                         local r, g, b = 0, 0, 0
                         b = SDL.And(c,255)
                         g = SDL.And(SDL.RShift(c,8),255)
                         r = SDL.And(SDL.RShift(c,16),255)
                         local t = {}
                         t.r = r
                         t.g = g
                         t.b = b
                         return t
                         end,
                   }
                 end,
                drawLine=function(x1,y1,x2,y2,couleur)
                     x,y=0
                     Dx,Dy=0;
    xincr,yincr=0;
    erreur=0;
    i=0;
	
	Dx = math.abs(x2-x1);
	Dy = math.abs(y2-y1);
	if (x1<x2) then
		xincr = 1;
	else
		xincr = -1;
	end
	if (y1<y2) then
		yincr = 1;
	else			
		yincr = -1;
     end
	x = x1;
	y = y1;
	if(Dx>Dy) then
		erreur = Dx/2;
		for i=0,Dx do
			x = x + xincr;
			erreur = erreur + Dy;
			if(erreur>Dx) then
				erreur = erreur - Dx;
				y = y+ yincr;
			end
			screen:pixel(x, y,couleur);
		end
	else
		erreur = Dy/2;
		for i=0,Dy do

			y = y+yincr;
			erreur = erreur + Dx;
		
			if(erreur>Dy) then
				erreur =erreur - Dy;
				x = x+xincr;
			end
			screen:pixel(surf,x, y,couleur);
		end
	end
  end
            }
  
  Image = {
        createEmpty = function (width, height)
            local surf = SDL.SDL_CreateRGBSurface(SDL_SWSURFACE, width, height, define_bpp, 0, 0, 0, 0);
            local w = width
            local h = height
            return a_img
        end,
        load = function (img)
		    tab=imagesdl.new()
            local rwop = SDL.SDL_RWFromFile(img, "rb")
			surf=SDL.IMG_Load_RW(rwop, 1)
            return tab
        end,
  }

  
  
  -------------------------------------
  
  Sound = {
    load = function (snd)
        local clip = SDL.Mix_LoadWAV(snd) 
        return {
            play = function () SDL.Mix_PlayChannel(0, clip, 0) end
        }
    end
  }
  
  --------------------------------------------
  
  
  
  Controls = {
    read = function (snd)
        event = SDL.SDL_Event_local()
        SDL.SDL_PollEvent(event)
        SDL.SDL_Delay(luaplayer.keyboard_delay)
        if event.type == SDL.SDL_QUIT then
            SDL.SDL_Quit()
			os.exit()
        end
        if event.type == SDL.SDL_KEYDOWN and event.key.keysym.sym == SDL.SDLK_ESCAPE then
            SDL.SDL_Quit()
			os.exit()
        end
        return {
		     mouseX = function ()
                return event.button.x
            end,
		     mouseY = function ()
                return event.button.y
            end,
            click = function ()
                if event.type == SDL.SDL_MOUSEBUTTONDOWN and event.button.button == SDL.SDL_BUTTON_LEFT then
                    return true
                else
                    return false
                end
            end,
            clickR = function ()
                if event.type == SDL.SDL_MOUSEBUTTONDOWN and event.button.button == SDL.SDL_BUTTON_RIGHT then
                    return true
                else
                    return false
                end
            end,
            up = function ()
                if event.type == SDL.SDL_KEYDOWN and event.key.keysym.sym == SDL.SDLK_UP then
                    return true
                else
                    return false
                end
            end,
            down = function ()
                if event.type == SDL.SDL_KEYDOWN and event.key.keysym.sym == SDL.SDLK_DOWN then
                    return true
                else
                    return false
                end
            end,
            left = function ()
                if event.type == SDL.SDL_KEYDOWN and event.key.keysym.sym == SDL.SDLK_LEFT then
                    return true
                else
                    return false
                end
            end,
            right = function ()
                if event.type == SDL.SDL_KEYDOWN and event.key.keysym.sym == SDL.SDLK_RIGHT then
                    return true
                else
                    return false
                end
            end,
            circle = function ()
                if event.type == SDL.SDL_MOUSEBUTTONDOWN and event.button.button == SDL.SDL_BUTTON_WHEELUP then
                    return true
                else
                    return false
                end
            end,
            cross = function ()
                if event.type == SDL.SDL_MOUSEBUTTONDOWN and event.button.button == SDL.SDL_BUTTON_WHEELDOWN then
                    return true
                else
                    return false
                end
            end,
            square = function ()
                if event.type == SDL.SDL_KEYDOWN and event.key.keysym.sym == SDL.SDLK_RALT then
                    return true
                else
                    return false
                end
            end,
            triangle = function ()
                if event.type == SDL.SDL_KEYDOWN and event.key.keysym.sym == SDL.SDLK_RCTRL then
                    return true
                else
                    return false
                end
            end,
            start = function ()
                if event.type == SDL.SDL_KEYDOWN and event.key.keysym.sym == SDL.SDLK_SPACE then
                    return true
                else
                    return false
                end
            end,
            select = function ()
                if event.type == SDL.SDL_KEYDOWN and event.key.keysym.sym == SDL.SDLK_ESCAPE then
                    return true
                else
                    return false
                end
            end,
            r = function ()
                if event.type == SDL.SDL_KEYDOWN and event.key.keysym.sym == SDL.SDLK_A then
                    return true
                else
                    return false
                end
            end,
            l = function ()
                if event.type == SDL.SDL_KEYDOWN and event.key.keysym.sym == SDL.SDLK_Z then
                    return true
                else
                    return false
                end
            end,
            analogX = function () return 0 end,
            analogY = function () return 0 end,
        }
        end
  }

  -- screen
  screen = {}
  function screen.waitVblankStart () end
  function screen.flip ()
	SDL.SDL_Flip(video)
	collectgarbage()
--	SDL.SDL_UpdateRect(video, 0, 0, 0, 0) 
  end
  function screen:blit (x,y,img,ox,oy,ow,oh)
    local s
    local d = SDL.SDL_Rect_local()
    d.x, d.y = x, y
    if ox and oy and ow and oh then
      s = SDL.SDL_Rect_local()
      s.x, s.y, s.w, s.h = ox, oy, ow, oh
    else
      s = nil
    end
    SDL.SDL_BlitSurface(img, s, video, d)
  end
  function screen:print (x,y,txt,fg)
    MiniFont:SetWindow(x, y, luaplayer.screen_width-x, luaplayer.screen_height-y) MiniFont:Print(txt) 
  end
  function screen:clear(color)
    local c = color or 0
    SDL.SDL_FillRect(video, nil, c)
  end
  function screen:fillRect(x, y, width, height, color)
    local c = color or 0
    local rect = SDL.SDL_Rect_local()
    rect.x, rect.y = x, y
    rect.w, rect.h = width, height
    SDL.SDL_FillRect(video, rect, c)
  end
  function screen:pixel(x, y)
    SDL.SDL_LockSurface(video)
    local c = SDL.SDL_GetPixel(video,x,y)
    SDL.SDL_UnlockSurface(video)
    return {
        colors = function ()
            local r, g, b = 0, 0, 0
            b = SDL.And(c,255)
            g = SDL.And(SDL.RShift(c,8),255)
            r = SDL.And(SDL.RShift(c,16),255)
            local t = {}
            t.r = r
            t.g = g
            t.b = b
            return t
        end,
    }
  end
   function screen:drawLine(x1,y1,x2,y2,couleur)
     x,y=0
    Dx,Dy=0;
    xincr,yincr=0;
    erreur=0;
    i=0;
	
	Dx = math.abs(x2-x1);
	Dy = math.abs(y2-y1);
	if (x1<x2) then
		xincr = 1;
	else
		xincr = -1;
	end
	if (y1<y2) then
		yincr = 1;
	else			
		yincr = -1;
     end
	x = x1;
	y = y1;
	if(Dx>Dy) then
		erreur = Dx/2;
		for i=0,Dx do
			x = x + xincr;
			erreur = erreur + Dy;
			if(erreur>Dx) then
				erreur = erreur - Dx;
				y = y+ yincr;
			end
			screen:pixel(x, y,couleur);
		end
	else
		erreur = Dy/2;
		for i=0,Dy do

			y = y+yincr;
			erreur = erreur + Dx;
		
			if(erreur>Dy) then
				erreur =erreur - Dy;
				x = x+xincr;
			end
			screen:pixel(surf,x, y,couleur);
		end
	end
  end
  function screen:fontPrint (font, x, y, txt, color)
print("not sure")
    MiniFont:SetWindow(x, y, luaplayer.screen_width-x, luaplayer.screen_height-y) 
    MiniFont:Print(txt)
print("not sure")
  end

  -- Timer (complete)
  Timer = {
        new = function (starttime)
            local measuredTime = os.time()
            local offset = starttime or 0
            return {
                start = function ()
                    if (measuredTime>0) then
                        return os.time() - measuredTime + offset
                    else
                        measuredTime = os.time()
                        return offset
                    end
                end,
                time = function ()
                    if (measuredTime>0) then
                        return os.time() - measuredTime + offset
                    else
                        return offset
                    end
                end,
                stop = function ()
                    if (measuredTime>0) then
                        offset = os.time() - measuredTime + offset
                        measuredTime = 0
                    end
                    return offset
                end,
                reset = function (starttime)
                    local result = nil
                    if (measuredTime>0) then
                        result = os.time() - measuredTime + offset
                    else
                        result = offset
                    end
                    measuredTime = os.time()
                    offset = starttime or 0
                    return result
                end,
            }
        end
  }

  -- System
  System = {}
  function System.currentDirectory(path)
    local result = lfs.currentdir()
    if path~=nil then
        lfs.chdir(path)
    end
    return result
  end
  function System.listDirectory(path)
    local result = {}
    local file = nil
    local path = path or lfs.currentdir()
    for file in lfs.dir(path) do
        if file ~= "." and file ~= ".." then
            local f = path..'/'..file
            local attr = lfs.attributes (f)
            assert (type(attr) == "table")
            local t={}
            t.name = file
            if attr.mode == "directory" then
                t.size = 0
                t.directory = true
            else
                t.size = attr.size
                t.directory = false
            end
            table.insert(result,t)
        end
    end
    return result
  end
  function System.createDirectory(path) return lfs.mkdir(path) end
  function System.removeDirectory(path) return lfs.rmdir(path) end
  function System.rename(oldName, newName) return os.rename(oldName, newName) end
  function System.removeFile(path) return os.remove(path) end
  function System.usbDiskModeActivate() print("No Usb disk available: failed to activate") end
  function System.usbDiskModeDeactivate() print("No Usb disk available: failed to deactivate") end
  function System.powerIsPowerOnline() return true end
  function System.powerIsBatteryExist() return true end
  function System.powerIsBatteryCharging() return false end
  function System.powerGetBatteryChargingStatus() return 0 end
  function System.powerIsLowBattery() return false end
  function System.powerGetBatteryLifePercent() return 0 end
  function System.powerGetBatteryLifeTime() return 0 end
  function System.powerGetBatteryTemp() return 0 end
  function System.powerGetBatteryVolt() return 0 end
  function System.powerTick() return 0 end
  function System.md5sum(String) print ("md5sum not yet used for luaplayer") end
  function System.sioInit(baudrate) print ("io port sioInit not yet used for luaplayer") end
  function System.sioWrite(string) print ("io port sioWrite not yet used for luaplayer") end
  function System.sioRead() print ("io port sioRead not yet used for luaplayer") end
  function System.sleep(number) ThreadWait(number) end
  function System.irdaInit() print ("irda port irdaInit not yet available for luaplayer") end
  function System.irdaWrite(string) print ("irda port irdaWrite not yet available for luaplayer") end
  function System.irdaRead() print ("irda port irdaRead not yet available for luaplayer") end
  function System.getFreeMemory() print ("getFreeMemory not yet available for luaplayer") end

