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


import java.util.Map;

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

import org.apache.commons.lang.StringUtils;

import com.google.common.collect.Maps;

import io.subutai.common.peer.ResourceHost;
import io.subutai.common.settings.SubutaiInfo;
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.ConfigManager;
import io.subutai.core.hubmanager.impl.HubManagerImpl;
import io.subutai.core.peer.api.PeerManager;
import io.subutai.hub.share.dto.VersionInfoDto;

import static java.lang.String.format;


public class VersionInfoProcessor extends HubRequester
{
    private static final Logger LOG = LoggerFactory.getLogger( VersionInfoProcessor.class );

    private static final Map<String, Object> VERSION_CACHE = Maps.newConcurrentMap();
    private static final String KEY_SSV = "ss_version";
    private static final String KEY_RHV = "rh_version";
    private static final String KEY_P2PV = "p2p_version";


    private ConfigManager configManager;

    private PeerManager peerManager;


    public VersionInfoProcessor( final HubManagerImpl hubManager, final PeerManager peerManager,
                                 final ConfigManager configManager, final RestClient restClient )
    {
        super( hubManager, restClient );

        this.peerManager = peerManager;
        this.configManager = configManager;
    }


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


    private void sendVersionInfo() throws HubManagerException
    {
        String path = format( "/rest/v1/peers/%s/version-info", peerManager.getLocalPeer().getId() );


        String ssV = "", rhV = "", p2pV = "";

        try
        {
            ResourceHost host = configManager.getPeerManager().getLocalPeer().getManagementHost();

            ssV = SubutaiInfo.getVersion();
            rhV = host.getRhVersion().replace( "Subutai version", "" ).trim();
            p2pV = host.getP2pVersion().replace( "p2p Cloud project", "" ).trim();
        }
        catch ( Exception e )
        {
            LOG.error( "Error getting system info: {}", e.getMessage() );
        }

        if ( areVersionsChanged( ssV, rhV, p2pV ) )
        {
            VersionInfoDto versionInfoDto = new VersionInfoDto();

            versionInfoDto.setPeerId( configManager.getPeerId() );
            versionInfoDto.setSsVersion( ssV );
            versionInfoDto.setRhVersion( rhV );
            versionInfoDto.setP2pVersion( p2pV );
            versionInfoDto.setBuildTime( SubutaiInfo.getBuildTime() );
            versionInfoDto.setBranch( SubutaiInfo.getBranch() );
            versionInfoDto.setCommitId( SubutaiInfo.getCommitId() );

            RestResult<Object> restResult = restClient.post( path, versionInfoDto );

            if ( restResult.isSuccess() )
            {
                if ( restResult.getEntity() != null && restResult.getEntity() instanceof String && StringUtils
                        .isNotBlank( ( String ) restResult.getEntity() ) )
                {
                    ( ( HubManagerImpl ) hubManager ).setPeerName( ( String ) restResult.getEntity() );
                    setChangedVersions( ssV, rhV, p2pV );
                }
            }
            else
            {
                throw new HubManagerException( "Error on sending version info to hub: " + restResult.getError() );
            }
        }
    }


    private boolean areVersionsChanged( String ssV, String rhV, String p2pV )
    {
        if ( VERSION_CACHE.get( KEY_SSV ) == null || !VERSION_CACHE.get( KEY_SSV ).equals( ssV ) )
        {
            return true;
        }


        if ( VERSION_CACHE.get( KEY_RHV ) == null || !VERSION_CACHE.get( KEY_RHV ).equals( rhV ) )
        {
            return true;
        }


        if ( VERSION_CACHE.get( KEY_P2PV ) == null || !VERSION_CACHE.get( KEY_P2PV ).equals( p2pV ) )
        {
            return true;
        }

        return false;
    }


    private void setChangedVersions( String ssV, String rhV, String p2pV )
    {
        VERSION_CACHE.put( KEY_SSV, ssV );
        VERSION_CACHE.put( KEY_RHV, rhV );
        VERSION_CACHE.put( KEY_P2PV, p2pV );
    }
}

@@ -46,16 +46,66 @@
 stor;%0A%0A%0A
+import java.util.Calendar;%0Aimport java.util.Date;%0A
 import j
@@ -1225,16 +1225,74 @@
 rsion%22;%0A
+    private static final String KEY_DATE = %22update_date%22;%0A
 %0A%0A    pr
@@ -4273,32 +4273,750 @@
 rue;%0A        %7D%0A%0A
+        //by force updates every 1 hour%0A        if ( VERSION_CACHE.get( KEY_DATE ) != null )%0A        %7B%0A            try%0A            %7B%0A                Date lastUpdate = ( Date ) VERSION_CACHE.get( KEY_DATE );%0A%0A                Calendar cal = Calendar.getInstance();%0A                cal.setTime( new Date() );%0A                cal.add( Calendar.HOUR, -1 );%0A                Date oneHourBack = cal.getTime();%0A%0A                if ( lastUpdate.before( oneHourBack ) )%0A                %7B%0A                    return true;%0A                %7D%0A            %7D%0A            catch ( Exception e )%0A            %7B%0A                LOG.error( e.getMessage() );%0A            %7D%0A        %7D%0A        else%0A        %7B%0A            return true;%0A        %7D%0A%0A
         return f
@@ -5237,20 +5237,71 @@
 PV, p2pV );%0A
+        VERSION_CACHE.put( KEY_DATE, new Date() );%0A
     %7D%0A%7D%0A

Improve verson info, send version info by force every hour