/*
 * (C) Copyright 2006-2009 Nuxeo SAS (http://nuxeo.com/) and contributors.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl.html
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * Contributors:
 *     Nuxeo - initial API and implementation
 *
 * $Id$
 */

package org.nuxeo.connect.client.status;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuxeo.connect.connector.http.ConnectUrlConfig;
import org.nuxeo.connect.data.DownloadablePackage;
import org.nuxeo.connect.data.SubscriptionStatusType;
import org.nuxeo.connect.identity.LogicalInstanceIdentifier;
import org.nuxeo.connect.identity.LogicalInstanceIdentifier.NoCLID;
import org.nuxeo.connect.packages.PackageManager;
import org.nuxeo.connect.update.PackageType;
import org.nuxeo.ecm.admin.runtime.PlatformVersionHelper;
import org.nuxeo.runtime.api.Framework;

/**
 * Store information about registration and possible updates
 *
 * @author Tiry (tdelprat@nuxeo.com)
 *
 */
public class ConnectUpdateStatusInfo {

    protected static final String UNREGISTERED ="unregistered";
    protected static final String ONLINE_REGISTERED ="onlineregistered";
    protected static final String CONNECT_UNREACHABLE="unreachable";
    protected static final String EXPIRED ="expired";

    protected String type;

    protected String bannerPath;

    protected Integer availableUpdateCount;

    protected String feedUrl;

    protected boolean registered;

    protected static Log log = LogFactory.getLog(ConnectUpdateStatusInfo.class);

    public static ConnectUpdateStatusInfo unregistered() {
        ConnectUpdateStatusInfo status = new ConnectUpdateStatusInfo();
        status.type=UNREGISTERED;
        status.setBannerPath("clientSideBanner");
        status.feedUrl = buildFeedUrl(false);
        status.availableUpdateCount=0;
        status.registered=false;
        return status;
    }

    public static ConnectUpdateStatusInfo ok() {
        ConnectUpdateStatusInfo status = new ConnectUpdateStatusInfo();
        status.type=ONLINE_REGISTERED;
        status.registered=true;
        return status;
    }

    public static ConnectUpdateStatusInfo connectServerUnreachable() {
        ConnectUpdateStatusInfo status = new ConnectUpdateStatusInfo();
        status.type=CONNECT_UNREACHABLE;
        status.setBannerPath("clientSideBanner");
        status.feedUrl = buildFeedUrl(true);
        status.availableUpdateCount=0;
        status.registered=true;
        return status;
    }

    public static ConnectUpdateStatusInfo notValid() {
        ConnectUpdateStatusInfo status = new ConnectUpdateStatusInfo();
        status.type=EXPIRED;
        status.setBannerPath("serverSideBanner");
        status.registered=true;
        return status;
    }


    protected static String buildFeedUrl(boolean registred) {

        StringBuffer sb = new StringBuffer();

        sb.append(Framework.getProperty("org.nuxeo.connect.client.feedUrl", ConnectUrlConfig.getBaseUrl()));
        sb.append("connect-gateway/jsonp/");


        if (registred) {
            sb.append("registered");
        } else {
            sb.append("unregistered");
        }

        sb.append("?product=");
        sb.append(PlatformVersionHelper.getPlatformFilter());
        if (registred) {
            sb.append("&instance=");
            try {
                sb.append(LogicalInstanceIdentifier.instance().getCLID1());
            } catch (NoCLID e) {
                log.error("Error in ConnectUpdateStatusInfo generation : No CLID is defined ...");
            }
        }

        sb.append("&callback=displayConnectUpdateStatus");
        return sb.toString();
    }

    public String getIdentifier() {
        try {
            return LogicalInstanceIdentifier.instance().getCLID1();
        } catch (NoCLID e) {
           return "";
        }
    }

    public String getDistributionLabel() {
        return PlatformVersionHelper.getDistributionName().toUpperCase() + " " + PlatformVersionHelper.getDistributionVersion();
    }

    public String getDistributionName() {
        return PlatformVersionHelper.getDistributionName().toUpperCase();
    }

    public String getDistributionVersion() {
        return PlatformVersionHelper.getDistributionVersion();
    }


    protected int compluteAvailableUpdateCount() {
        if (!ConnectStatusHolder.instance().getStatus().isConnectServerUnreachable()) {
            return 0;
        }
        PackageManager pm = Framework.getLocalService(PackageManager.class);

        List<DownloadablePackage> pkgs = pm.listUpdatePackages(PackageType.HOT_FIX);

        List<DownloadablePackage> localHotFixes = pm.listLocalPackages(PackageType.HOT_FIX);

        List<DownloadablePackage> applicablePkgs = new ArrayList<DownloadablePackage>();

        for (DownloadablePackage pkg : pkgs) {
            if (PlatformVersionHelper.isCompatible(pkg.getTargetPlatforms())) {
                boolean isInstalled = false;
                for (DownloadablePackage localPkg : localHotFixes) {
                    if (localPkg.getId().equals(pkg.getId())) {
                        isInstalled=true;
                        break;
                    }
                }
                if (!isInstalled) {
                    applicablePkgs.add(pkg);
                }
            }
        }
        return applicablePkgs.size();
    }


    public String getBannerPath() {
        return bannerPath;
    }

    protected void setBannerPath(String bannerName) {
        if (!bannerName.startsWith("/")) {
            bannerPath = "/incl/" + bannerName;
        } else {
            bannerPath = bannerName;
        }
        if (!bannerPath.endsWith(".xhtml")) {
            bannerPath = bannerPath + ".xhtml";
        }
    }

    public int getAvailableUpdateCount() {
        if (availableUpdateCount==null) {
            availableUpdateCount = compluteAvailableUpdateCount();
        }
        return availableUpdateCount;
    }

    public String getType() {
        return type;
    }

    public String getFeedUrl() {
        return feedUrl;
    }

    public boolean isRegistered() {
        return registered;
    }

    public boolean isExpired() {
        return ConnectStatusHolder.instance().getStatus().status() == SubscriptionStatusType.EXPIRED;
    }
}

@@ -4765,25 +4765,24 @@
 ted int comp
-l
 uteAvailable
@@ -4809,17 +4809,16 @@
     if (
-!
 ConnectS
@@ -6365,17 +6365,16 @@
 t = comp
-l
 uteAvail

fix how we check is connect server is reachable