dofile('data/Lua/Constants.lua')
dofile('data/Lua/Helpers.lua')
dofile('data/Lua/Inventory.lua')
dofile('data/Lua/FunctionDispatcher.lua')
dofile('data/Lua/Comics.lua')
dofile('data/Lua/LevelBasicPolicies.lua')
dofile('data/Lua/ReferenceCounter.lua')
dofile('data/Lua/Profile.lua')
dofile('data/Lua/ProfileManager.lua')
dofile('data/Lua/Console.lua')

local date = os.date('*t')
math.randomseed(os.clock() + date.sec + date.min + date.hour + date.day + date.month + date.year)
local levels = {}
--levels[0] = 'data/Scenes/test.lua'
levels[1] = 'data/Scenes/1_museum_gallery_1.lua'
levels[2] = 'data/Scenes/2_crime_place_1.lua'
levels[2.5] = ''
levels[3] = 'data/Scenes/3_sheriff_cabinet_2.lua'
levels[4] = 'data/Scenes/4_directors_museum_office_2.lua'
levels[5] = 'data/Scenes/5_guard_room_2.lua'
levels[5.5] = ''
levels[6] = 'data/Scenes/6_cabinet_chief_repair_3.lua'
levels[7] = 'data/Scenes/7_ locker_room_repairers_3.lua'
levels[8] = 'data/Scenes/8_basement_3.lua'
--levels[8.1] = 'data/Scenes/Survey_final.lua'
levels[8.5] = ''
levels[9] = 'data/Scenes/9_ room_telephone_operator_4.lua'
levels[10] = 'data/Scenes/10_electric_shield_4.lua'
levels[10.5] = 'data/Scenes/10.5_electric_shield_4.lua'
levels[10.6] = ''
levels[11] = 'data/Scenes/11_call_box_5.lua'
levels[11.5] = 'data/Scenes/11.5_call_box_5.lua'
levels[12] = 'data/Scenes/12_security_5.lua'
levels[13] = 'data/Scenes/13_ chamber_octopus_5.lua'
levels[13.5] = ''
levels[14] = 'data/Scenes/14_ pharmacy_counter_6.lua'
levels[15] = 'data/Scenes/15_ pharmacy_laboratory.lua'
levels[15.5] = ''
levels[16] = 'data/Scenes/16_ room_helper_7.lua'
levels[17] = 'data/Scenes/17_ room_cook_7.lua'
levels[17.5] = ''
levels[18] = 'data/Scenes/18_gas_station_8.lua'
levels[19] = 'data/Scenes/19_ gas-station_ shop_8.lua'
levels[19.5] = ''
levels[20] = 'data/Scenes/20_bar_proof_9.lua'
levels[21] = 'data/Scenes/21_ distant_dinner-wagon_9.lua'
levels[22] = 'data/Scenes/22_base_court_9.lua'
levels[22.5] = ''
levels[23] = 'data/Scenes/23_ dump_cars_10.lua'
levels[24] = 'data/Scenes/24_caravan_workers_10.lua'
levels[25] = 'data/Scenes/25_wall_10.lua'
levels[25.5] = ''
levels[26] = 'data/Scenes/26_ garret_11.lua'
levels[27] = 'data/Scenes/27_room_11.lua'
levels[28] = 'data/Scenes/28_basement_laundry_11.lua'
levels[28.5] = ''
levels[29] = 'data/Scenes/29_reception_12.lua'
levels[30] = 'data/Scenes/30_reading_room_12.lua'
levels[31] = 'data/Scenes/31_roof_12.lua'
levels[31.5] = ''
levels[32] = 'data/Scenes/32_cathedral_13.lua'
levels[33] = 'data/Scenes/33_after_altar_13.lua'
levels[34] = 'data/Scenes/34_ cave_13.lua'
levels[34.5] = 'data/Scenes/34.5_ cave_13.lua'
levels[34.6] = ''
levels[35] = 'data/Scenes/35_ pond_14.lua'
levels[36] = 'data/Scenes/36_laboratory_14.lua'
levels[37] = 'map'

local table_buffer = {}

function GetLevelsCount()
    local result = 0;
    for i, v in pairs(levels) do
		if math.floor(i) == i and v ~= "map" then
			result = result + 1
		end
    end    
    return result
end

function PrepareTableBuffer()
    if table.getn(table_buffer) ~= 0 then
        return
    end
    for i, v in pairs(levels) do
        table.insert(table_buffer, i);
    end -- for
    table.sort(table_buffer);
end

function GetLevelToLoad()
	PrepareTableBuffer();
	
	return levels[1];
end

function GetCurLevelId(cur_level)
    PrepareTableBuffer()
    for i, v in pairs(levels) do
        if cur_level == v then
            -- тут делаем поиск по таблице буферных индексов
            for k, w in pairs(table_buffer) do
                if i == w then
					return k, w
                end
            end
        end
    end
    
    assert('Sensey: Noexist next level');
end

function GetNextLevel(cur_level)
	local k, r = GetCurLevelId(cur_level)
    if k == table.maxn(table_buffer) then
		--TEMP
		--[[for i, v in pairs(levels) do
		   StartLevel( v ); 
		   break
		end]]
        return levels[1]
	else
	    local level_id = levels[ table_buffer[k + 1] ]
	    if level_id ~= "" then
	        return level_id
	    else
	        return nil
	    end
	end	
end

function StartNextLevel(cur_level)
	local level = GetNextLevel(cur_level)
	if not level then
		return false
	elseif level == "map" then
		local timer = play_field:GetTimer()
		GetProfileManager():GetCurrentProfile().last_level_completed_ = play_field:GetName()
        local destroy_current_level = 'play_field:GetLevelScreen():ScreenDestroy()'
        local load_gm = "load_screen('data/Lua/Screens/GlobalMap.lua')"
        GTimerDoString(destroy_current_level..' '..load_gm, 0.5)
        return true
	end
	StartLevel(level)
	return true
end

function GetLevelPath(id)
	return levels[table_buffer[id]]
end

function GetLevelByRealId(r)    
    return levels[r]
end

function FinishLevel(cur_level)
    if StartNextLevel(cur_level) then
        return
    end
    local load_screen
	local screen_path = 'data/Lua/Screens/Movie.lua'
	GetProfileManager():GetCurrentProfile().last_level_completed_ = play_field:GetName()
	if play_field then
        local timer = play_field:GetTimer()
        local destroy_current_level = 'play_field:GetLevelScreen():ScreenDestroy()'
        local load_next_level = "load_screen('"..screen_path.."')"
        GTimerDoString(destroy_current_level..' '..load_next_level, 0.5)
    else
        GetGameManager():GetCurrentScreen():Destroy()
        load_screen(screen_path);
    end
end

function GetFirstLevelPath()
    return 'data/Scenes/1_booth.lua'
end

function LoadCommonResources()
	AddAnimation()
	AddSprite()
end

function PrecacheMenuResources()
    GetTexture('data/Texture/GUI/Menu/BG.jpg')
    GetTexture('data/Texture/GUI/Menu/Buttons/exit.png')
    GetTexture('data/Texture/GUI/Menu/Buttons/credits.png')
    GetTexture('data/Texture/GUI/Menu/Buttons/play.png')
    GetTexture('data/Texture/GUI/Menu/Buttons/options.png')
    GetTexture('data/Texture/GUI/Menu/Buttons/profile.png')
    GetTexture('data/Texture/GUI/Menu/Animations/most.png')
    GetTexture('data/Texture/GUI/Menu/Logo.jpg')
    GetTexture('data/Texture/GUI/Menu/back_menu_4.png')
    GetTexture('data/Texture/GUI/Menu/back_menu_3.png')
    GetTexture('data/Texture/GUI/Menu/back_menu_2.png')
    GetTexture('data/Texture/GUI/Menu/Animations/stars.png')
    GetTexture('data/Texture/GUI/Menu/Animations/ad/ad.png')
    GetTexture('data/Texture/GUI/Menu/Wheels/004.png')
    GetTexture('data/Texture/GUI/Menu/Wheels/005.png')
    GetTexture('data/Texture/GUI/Menu/Wheels/003.png')
    GetTexture('data/Texture/GUI/Menu/Wheels/002.png')
    GetTexture('data/Texture/GUI/Menu/Wheels/001.png')
end

function GetLevelPathByID(id)
	for i, path in pairs(levels) do
		if i == id then
			return path
		end
	end
	return nil
end

--[[
do
   local oldrandom = math.random
   local randomtable
   math.random = function()
      if randomtable == nil then
         randomtable = {}
         for i = 1, 97 do
            randomtable[i] = oldrandom()
         end
      end
      local x = oldrandom()
      local i = 1 + math.floor(97 * x)
      x, randomtable[i] = randomtable[i], x
      return x
   end
end
--]]

function IsLevelCompleted(levelName)
	local completed  = false
	
	if GetProfileManager():GetCurrentProfile().last_level_completed_ ~= "" then
        local i, r = GetCurLevelId(GetProfileManager():GetCurrentProfile().last_level_completed_)
        
        local k, r = GetCurLevelId(levelName)
        if k <= i then
            completed = true
        end
    end
	return completed
end

function StartLevelById(id)
    GetProfileManager():GetCurrentProfile():OnRestart()

    local id = tonumber(id)
	local path = GetLevelPathByID(id)
    if path == nil then
		Console:Log("There is no level with id ".. id)
	else
		StartLevel(path)
	end
end