package io.subutai.core.hubmanager.impl.requestor;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import io.subutai.common.command.CommandException;
import io.subutai.common.peer.ContainerHost;
import io.subutai.common.peer.ResourceHost;
import io.subutai.common.settings.Common;
import io.subutai.core.desktop.api.DesktopManager;
import io.subutai.core.hubmanager.api.HubRequester;
import io.subutai.core.hubmanager.api.RestClient;
import io.subutai.core.hubmanager.api.RestResult;
import io.subutai.core.hubmanager.api.exception.HubManagerException;
import io.subutai.core.hubmanager.impl.HubManagerImpl;
import io.subutai.core.peer.api.PeerManager;
import io.subutai.hub.share.dto.environment.ContainerStateDto;
import io.subutai.hub.share.dto.environment.container.ContainerDesktopInfoDto;
import io.subutai.hub.share.dto.environment.container.ContainerEventDto;


public class ContainerEventProcessor extends HubRequester
{
    private final Logger log = LoggerFactory.getLogger( getClass() );

    private PeerManager peerManager;
    private DesktopManager desktopManager;


    public ContainerEventProcessor( final HubManagerImpl hubManager, final PeerManager peerManager,
                                    final RestClient restClient, final DesktopManager desktopManager )
    {
        super( hubManager, restClient );
        this.peerManager = peerManager;
        this.desktopManager = desktopManager;
    }


    @Override
    public void request() throws HubManagerException
    {
        process();
    }


    public void process() throws HubManagerException
    {
        try
        {
            for ( ResourceHost rh : peerManager.getLocalPeer().getResourceHosts() )
            {
                sendContainerStates( rh );
            }
        }
        catch ( Exception e )
        {
            log.error( "Oops error: ", e.getMessage() );
        }
    }


    private void sendContainerStates( ResourceHost rh ) throws HubManagerException
    {
        log.info( "ResourceHost: id={}, hostname={}, containers={}", rh.getId(), rh.getHostname(),
                rh.getContainerHosts().size() );

        for ( ContainerHost ch : rh.getContainerHosts() )
        {
            if ( !Common.MANAGEMENT_HOSTNAME.equals( ch.getContainerName() ) )
            {
                sendContainerState( ch );
            }
        }
    }


    private void sendContainerState( ContainerHost ch ) throws HubManagerException
    {
        log.info( "- ContainerHost: id={}, name={}, environmentId={}, state={}", ch.getId(), ch.getContainerName(),
                ch.getEnvironmentId(), ch.getState() );

        ContainerStateDto state = ContainerStateDto.valueOf( ch.getState().name() );
        ContainerEventDto dto = new ContainerEventDto( ch.getId(), ch.getEnvironmentId().getId(), state );

        if ( !desktopManager.existInCache( ch.getId() ) )
        {
            try
            {
                //get information about desktop env and remote desktop server
                String deskEnv = desktopManager.getDesktopEnvironmentInfo( ch );
                String rDServer = desktopManager.getRDServerInfo( ch );

                if ( !deskEnv.isEmpty() && !rDServer.isEmpty() )
                {
                    //add to cache as a desktop container
                    desktopManager.containerIsDesktop( ch.getId() );

                    ContainerDesktopInfoDto desktopInfo = new ContainerDesktopInfoDto( ch.getId(), deskEnv, rDServer );
                    dto.setDesktopInfo( desktopInfo );
                    try
                    {
                        desktopManager.createDesktopUser( ch );
                    }
                    catch ( Exception e )
                    {
                        log.error( e.getMessage() );
                    }
                }
                else
                {
                    //add to cache as not desktop container
                    desktopManager.containerIsNotDesktop( ch.getId() );
                }
            }
            catch ( CommandException e )
            {
                log.error( e.getMessage() );
            }
        }

        try
        {
            desktopManager.copyKeys( ch );
        }
        catch ( CommandException e )
        {
            log.error( "Could not copy SSH keys to x2go usr" );
        }

        RestResult res = doRequest( dto );

        log.info( "Response status: {}", res.getStatus() );
    }


    private RestResult doRequest( ContainerEventDto dto ) throws HubManagerException
    {
        try
        {
            String path = String.format( "/rest/v1/containers/%s/events", dto.getContainerId() );

            return restClient.post( path, dto );
        }
        catch ( Exception e )
        {
            throw new HubManagerException( e );
        }
    }
}

@@ -2818,24 +2818,58 @@
 , state );%0A%0A
+        Boolean isDesktop = null;%0A
         if (
@@ -2910,24 +2910,24 @@
 getId() ) )%0A
-
         %7B%0A  
@@ -3331,78 +3331,8 @@
 ner%0A
-                    desktopManager.containerIsDesktop( ch.getId() );%0A%0A
     
@@ -3765,32 +3765,70 @@
               %7D%0A
+                    isDesktop = true;%0A
                 
@@ -3952,58 +3952,25 @@
     
-desktopManager.containerIsNotDesktop( ch.getId() )
+isDesktop = false
 ;%0A  
@@ -4313,32 +4313,32 @@
 %22 );%0A        %7D%0A%0A
-
         RestResu
@@ -4361,24 +4361,313 @@
 st( dto );%0A%0A
+        if ( isDesktop != null )%0A        %7B%0A            if ( isDesktop )%0A            %7B%0A                desktopManager.containerIsDesktop( ch.getId() );%0A            %7D%0A            else%0A            %7B%0A                desktopManager.containerIsNotDesktop( ch.getId() );%0A            %7D%0A        %7D%0A%0A
         log.

save desktop info cache after sending data to Bazaar