TIME_SHOW_COMICS=0.3
TIME_MOVE_SMS = 0.4

NAME_STATE_COMICS = 'Comics_('

function GetNameStateComics()
    local scene_path = play_field:GetName()
    
    return NAME_STATE_COMICS..scene_path..')_'
end

function LoadComics(path, name)
    if name == nil then
        name = path
    end
    
    local scene_path = play_field:GetName()
    if HasGameState(GetNameStateComics()..name, 'show') and HasGameState(GetNameStateComics()..name, 'hide') then
        return nil
    end
    if game_state.comics then
        return nil
    end        
    
    AddGameState(GetNameStateComics()..name, 'show')
    SaveStatesPlayField()
                                            
    local screen_comics = load_screen(path)
    assert(screen_comics)
    screen_comics:SetLayer(LAYER_COMICS)
    screen_comics.replic = name
    game_state.comics = screen_comics
    play_field:SetEnabled(false)
    --play_field:GetLevelScreen():GetPanel():Stop()
    play_field:GetLevelScreen():GetPanel():SetAllowInput(false)
    play_field:HideHint()
    
    SetCursor(GetCursorArrow())
    
    return screen_comics
end

function LoadComicsWithOneReplicHeroes(path, replic)
    local screen = LoadComics(path, replic)
    if screen ~= nil then
        CreateOneReplicHeroes(replic)
    end
    
    return screen
end

function LoadComicsWithOneSMS(path, replic)
    local screen = LoadComics(path, replic)
    if screen ~= nil then
        CreateOneSMS(replic)
    end
    
    return screen
end

function IsExistComics()
    return game_state.comics
end

function FinishComics(hidden_comics)
    if game_state.comics then
        --local name_comics = game_state.comics:GetName()
        local name_comics = game_state.name_comics
        local replic = game_state.comics.replic
    
        play_field:GetLevelScreen():Go()
        game_state.comics:ScreenDestroy()
        game_state.comics = nil
        ReloadStatesPlayField()
        play_field:SetEnabled(true)
        play_field:GainFocus()
        play_field:GetLevelScreen():GetPhone():Go()
        --play_field:GetLevelScreen():GetPanel():Go()
        play_field:GetLevelScreen():GetPanel():SetAllowInput(true)
        
        screen_comics = nil
        if hidden_comics ~= nil and hidden_comics then
            local time_hide = 0.5
            local state = GetNameStateComics()..replic
            --AddGameState(GetNameStateComics()..replic, 'hide')
            local comics = GetComics(replic)
            if comics == nil then
                comics = GetComics(game_state.name_comics)
            end
            TimerDo(play_field:GetTimer(), 0.5, function()
                                                    if comics and comics.bRepeat == false then
                                                        AddGameState(state, 'hide')
                                                    end
                                                    OnHiddenComics(replic)
                                                    if comics then
                                                        if comics.bRepeat == false then
                                                            AddGameState(GetNameStateComics()..comics.name, 'played')
                                                        end
                                                        comics:OnHidden()
                                                    end
                                                end)
            if comics and comics.bRepeat == true then
                RemoveGameState(GetNameStateComics()..replic, 'show')
                RemoveGameState(GetNameStateComics()..replic, 'hide')
                RemoveGameState(GetNameStateComics()..comics.name, 'played')
                RemoveGameState(GetNameStateComics()..game_state.name_comics, 'show')
                RemoveGameState(GetNameStateComics()..game_state.name_comics, 'hide')
                RemoveGameState(GetNameStateComics()..game_state.name_comics, 'played')
            end
            if comics and comics.bRepeat == false then
                comics.played = true
            end
        end
    end
end

function RegisterComics(name, function_init)
    local comics = {}
    comics.name = name
    comics.function_init = function_init
    comics.bRepeat = false

    table.insert(game_state.register_comics, comics)
    AssignRegisterComicsMethods(comics)
    
    -- Проверка на запуск
    if  HasGameState(GetNameStateComics()..name, 'show') and 
        not HasGameState(GetNameStateComics()..name, 'hide')
    then
        TimerDo(play_field:GetTimer(), TIME_START_LEVEL, function() 
                                                            PlayRegisterComics(name)
                                                          end )
    end
    
    return comics
end

function RegisterComicsEx(function_init)
    local comics = {}
    comics.name = game_state.scene_path..'_comics_'..table.maxn(game_state.register_comics)
    comics.function_init = function_init
    comics.bRepeat = false
    comics.played = false

    table.insert(game_state.register_comics, comics)
    AssignRegisterComicsMethods(comics)
    
    -- Проверка на запуск
    if  HasGameState(GetNameStateComics()..comics.name, 'show') and 
        not HasGameState(GetNameStateComics()..comics.name, 'hide')
    then
        TimerDo(play_field:GetTimer(), TIME_START_LEVEL, function() 
                                                            comics:Play()
                                                          end )
    end
    
    if HasGameState(GetNameStateComics()..comics.name, 'played') then
        comics.played = true
    end
    
    return comics
end

function GetComics(name)
--[[
    if game_state.register_comics == nil then
        return nil
    end
]]
    for i, v in ipairs(game_state.register_comics) do
        if v.name == name then
            return v
        end
    end
    
    return nil
end

function PlayRegisterComics(name)
    for i, v in ipairs(game_state.register_comics) do
        if v.name == name then
            v.function_init()
            game_state.name_comics = name
            break;
        end
    end
end

function AssignRegisterComicsMethods(comics)
    comics.Play = function()
        if comics.played then
            return;
        end
    
        comics.function_init()
        if game_state.comics then
            --game_state.comics:SetName(comics.name);
            game_state.name_comics = comics.name
            --game_state.comics.replic = comics.name;
        end
        if not comics.bRepeat then
            AddGameState(GetNameStateComics()..comics.name, 'show')
        end
    end
    
    comics.OnHidden = function()
    end
    
    comics.SetRepeat = function(value)
        comics.played = false
        if value then
            comics.bRepeat = true
        else
            comics.bRepeat = false
        end
    end
    
end

--------------------------------------------------------------------------------------------
-- Init comics techo
--------------------------------------------------------------------------------------------

ComicsTecho = {};

function ComicsTecho:New(type)
    local result = CreateObjectOfClass(self)
    result.objects = {}
    result.af = nil
    result.type = type
    result.is_close = false
    result.is_show = false
    result.bg_phone = nil
    result.lazer = nil
    result.boy = nil
    result.text = nil
    result.text_buffer = {}
    
    local screen = GetGameManager():GetCurrentScreen()
    local based = CreateAutoRegisterEntity()
    based:AttachTo(screen)
    based:SetOpacity(0)
    result.based = based

    return result
end

function ComicsTecho:GetBased()
    return self.based
end

function ComicsTecho:Show()
    self.lazer:Play()
    local lazer_duration = self.lazer:GetDuration()
    self.based:SetOpacity(1)

    local af_based = CreateAnimationEffector()
    af_based:AttachTo(self.text)
    af_based:SetKey(_TRACK_O, 0,                        0.01)
    af_based:SetKey(_TRACK_O, lazer_duration/5,         0)
    af_based:SetKey(_TRACK_O, lazer_duration/2 + 0.1,   1)
    af_based:Play()
    self.af = af_based

    for i, v in pairs(self.objects) do
        local af = CreateAnimationEffector()
        af:AttachTo(v)
        af:SetKey(_TRACK_O, 0,                        0.01)
        af:SetKey(_TRACK_O, lazer_duration/5,         0)
        af:SetKey(_TRACK_O, lazer_duration/2 + 0.1,   1)
        af:Play()
    end
end

function ComicsTecho:ShowSMS()
    local based = self.based;
        
    local af = CreateAnimationEffector()
    af:AttachTo(self.based)
    af:SetKey(_TRACK_O, 0.,             1)
    af:SetKey(_TRACK_X, 0.0,            self.based:GetX() - 1000)
    af:SetKey(_TRACK_Y, 0.0,            self.based:GetY())
    af:SetKey(_TRACK_X, TIME_MOVE_SMS,  self.based:GetX())
    af:SetKey(_TRACK_Y, TIME_MOVE_SMS,  self.based:GetY())
    af:Play()
    self.af = af

    PlaySound('sms_open')
end

function ComicsTecho:Play()
    self.is_show = true;
    if self.type then
        if self.type == 'sms' then
            self:ShowSMS()
            return;
        end
    end
    self:Show()
end

function ComicsTecho:Close()
    self.is_close = true;
    if self.type then
        if self.type == 'sms' then
            self:HideSMS()
            return
        end
    end
    self:Hide()
end

function ComicsTecho:IsClose()
    return self.is_close
end

function ComicsTecho:IsShow()
    return self.is_show
end

function ComicsTecho:IsPlaying()
    if self.af == nil then
        return false
    end
    
    return not self.af:IsPaused()
end

function ComicsTecho:Hide()
    local based = self.based

    if table.getn(self.text_buffer) ~= 0 then
        local af = CreateAnimationEffector()
        af:AttachTo(self.text)
        af:SetKey(_TRACK_O, 0.0,   1)
        af:SetKey(_TRACK_O, 0.3,   0)
        af:SetKey(_TRACK_O, 0.6,   1)
        af:Play()
        self.af = af
        
        TimerDo(game_state.comics:GetTimer(), 0.3, function()
                                                        local  text = self.text_buffer[1]
                                                        self.text:SetText(text)
                                                        table.remove(self.text_buffer, 1)
                                                   end)
        self.is_close = false
        return
    end

    local af = CreateAnimationEffector()
    af:AttachTo(based)
    af:SetKey(_TRACK_O, 0,                1)
    af:SetKey(_TRACK_O, TIME_SHOW_COMICS, 0)
    af:Play()
    self.af = af
end

function ComicsTecho:HideSMS()
    local based = self.based
        
    local af = CreateAnimationEffector()
    af:AttachTo(based)
    af:SetKey(_TRACK_X, 0.0,            self.based:GetX())
    af:SetKey(_TRACK_Y, 0.0,            self.based:GetY())
    af:SetKey(_TRACK_X, TIME_MOVE_SMS,  self.based:GetX() - 1000)
    af:SetKey(_TRACK_Y, TIME_MOVE_SMS,  self.based:GetY())
    af:Play()
    self.af = af
end

function ComicsTecho:AddObject(object)
    table.insert(self.objects, object)
end

function ComicsTecho:CreateObject(path, name, pos_x, pos_y, pos_z)
    local screen = GetGameManager():GetCurrentScreen()
    local anim = CreateAnimationByPath(path)
    local anim_width = anim:GetWidth()
    local anim_height = anim:GetHeight()
    anim:SetHotSpot(anim_width/2,anim_height/2)
    local obj = screen:CreateObject(name,anim,pos_x, pos_y, pos_z,0,1,1)
    obj:AttachTo( self.based )
    self:AddObject(obj)
end

function ComicsTecho:GetObject(name)
    if self.objects then
        for i, v in pairs(self.objects) do
            if v:GetName() == name then
                return v
            end
        end
    end

    return nil
end

function ComicsTecho:GetOpacity()
    return self.based:GetOpacity()
end

function ComicsTecho:SetPersonageBoy(index, text)
    local screen = GetGameManager():GetCurrentScreen()
    
    if index == nil then
        index = 1
    end
	
	self.lazer = createCompositionLazer()
	self.lazer:AttachTo(self.based)
	self.lazer:SetZ(50)
	
	if text ~= nil then
	    local text_width = 670
	    local text_height = 70
	
	    local textComics = CreateTextEntity("CenturySch24", '')
        textComics:AttachTo( self.based )
        textComics:SetScale(1)
        textComics:SetZ(200)
        textComics:SetXY(330, 675)
        textComics:SetBorderSize(text_width, text_height)
        textComics:SetTextAlignment(HGETEXT_MIDDLE + HGETEXT_LEFT)
	    self.text = textComics
	    
        local v = textComics:ExplodeText(text, text_width, text_height)
        textComics:SetText(v:get(0))
        self.text_buffer = {}
        for i = 1, v:size() - 1 do
            table.insert(self.text_buffer, v:get(i))
        end

        local anim = CreateAnimation('data/Texture/Comics/boy.png',0,0,87,87,1,0)
        anim:SetHotSpot(43,43)
        anim:SetBlendMode(2)
        anim:SetColor('0xFFFFFFFF')
        local obj_boy = screen:CreateObject('boy'..index..text,anim,272,706,250,0,1,1)
        obj_boy:AttachTo( self.based )
        self:AddObject(obj_boy)
        self.boy = obj_boy
	end
end

function ComicsTecho:SetPersonageProfessor(index, text)
    local screen = GetGameManager():GetCurrentScreen()
    
    if index == nil then
        index = 1
    end
	
	self.lazer = createCompositionLazer()
	self.lazer:AttachTo(self.based)
	self.lazer:SetZ(50)
	
	if text ~= nil then
	    local text_width = 670
	    local text_height = 70
	
	    local textComics = CreateTextEntity("CenturySch24", '')
        textComics:AttachTo( self.based )
        textComics:SetScale(1)
        textComics:SetZ(200)
        textComics:SetXY(330, 675)
        textComics:SetBorderSize(text_width, text_height)
        textComics:SetTextAlignment(HGETEXT_MIDDLE + HGETEXT_LEFT)
	    self.text = textComics
	    
        local v = textComics:ExplodeText(text, text_width, text_height)
        textComics:SetText(v:get(0))
        self.text_buffer = {}
        for i = 1, v:size() - 1 do
            table.insert(self.text_buffer, v:get(i))
        end

        local anim = CreateAnimation('data/Texture/Comics/professor.png',0,0,87,87,1,0)
        anim:SetHotSpot(42,42)
        anim:SetBlendMode(2)
        anim:SetColor('0xFFFFFFFF')
        local obj_proffesor = screen:CreateObject('boy'..index..text,anim,272,706,250,0,1,1)
        obj_proffesor:AttachTo( self.based )
        self:AddObject(obj_proffesor)
        self.boy = obj_boy
	end
end

function ComicsTecho:SetPersonage_Girl_1(index, text)
    local screen = GetGameManager():GetCurrentScreen()
    
    if index == nil then
        index = 1
    end
	
	self.lazer = createCompositionLazer()
	self.lazer:AttachTo(self.based)
	self.lazer:SetZ(50)
	
	if text ~= nil then
	    local text_width = 760
	    local text_height = 70
	
	    local textComics = CreateTextEntity("CenturySch24", text)
	    textComics:AttachTo( self.based )
	    textComics:SetScale(1)
	    textComics:SetZ(self.lazer:GetZ() + 100)
	    textComics:SetXY(230, 675)
	    textComics:SetBorderSize(text_width, text_height)
	    textComics:SetTextAlignment(HGETEXT_MIDDLE + HGETEXT_LEFT)
	    self.text = textComics
	    
        local v = textComics:ExplodeText(text, text_width, text_height)
        textComics:SetText(v:get(0))
        self.text_buffer = {}
        for i = 1, v:size() - 1 do
            table.insert(self.text_buffer, v:get(i))
        end        
	end
end

function ComicsTecho:CreateSMS(text, index)
    local screen = GetGameManager():GetCurrentScreen()
    local based = self.based

    self:SetBgPhone('data/Texture/Comics/animation/sms/message.png', 'message'..index)
--[[    
    local anim = CreateAnimation('data/Texture/Comics/animation/sms/message.png',0,0,494,383,1,0)
	anim:SetHotSpot(247,191)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	local bg_phone = screen:CreateObject('message'..index,anim,592,311,120,0,1,1)
	bg_phone:AttachTo(self.based)
	self.bg_phone = bg_phone
]]
	if text then
        local textSMS = CreateTextEntity("Arial18", text)
        textSMS:SetName('sms_' .. index)
        textSMS:AttachTo( self.based )
        textSMS:SetScale(1)
        textSMS:SetZ(1300)
        textSMS:SetXY(390, 350)
        textSMS:SetBorderSize(420, 80 )
        textSMS:SetTextAlignment(HGETEXT_TOP + HGETEXT_LEFT)
        self:AddObject(textSMS)
    end
end

function ComicsTecho:SetBgPhone(path, name)
    if self.bg_phone then
        self.bg_phone:SetVisible(false)
--      self.bg_phone = nil
    end

    local screen = GetGameManager():GetCurrentScreen()
    local based = self.based
    local anim = CreateAnimation(path,0,0,494,383,1,0)
	anim:SetHotSpot(247,191)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	local bg_phone = screen:CreateObject(name,anim,592,311,120,0,1,1)
	bg_phone:AttachTo(self.based)
	self.bg_phone = bg_phone
end

--------------------------------------------------------------------------------------------
-- Init AutoGeneratorComics techo
--------------------------------------------------------------------------------------------

AutoGeneratorComics = {};

function AutoGeneratorComics:New()
    local result = CreateObjectOfClass(self);
    result.buffer = {};
    
    return result;
end

function AutoGeneratorComics:AddObject(object)
    table.insert(self.buffer, object);
end

function AutoGeneratorComics:PlayNext()
    local buffer = self.buffer;
    for i, v in pairs(buffer) do
        if not v:IsClose() and not v:IsPlaying() and v:IsShow() then
            v:Close();
            break;
        end    
    end -- for i, v in pairs(buffer) do
end

function AutoGeneratorComics:Update(dt)
    local buffer = self.buffer;
    for i, v in pairs(buffer) do
        if v:IsClose() then
            break
        end
        if not v:IsShow() and not v:IsPlaying() then
            v:Play()
        end
        break;
    end -- for i, v in pairs(buffer) do
    
    for i, v in pairs(buffer) do
        if v:IsClose() and v:IsShow() and not v:IsPlaying() then
            table.remove(buffer, i)
        end
    end

    if #buffer == 0 then
        return true
    end
    
    return false
end

--------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------

