/*
 * Copyright (C) 2005-2010 Alfresco Software Limited.
 *
 * This file is part of Alfresco
 *
 * Alfresco is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Alfresco 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.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Alfresco. If not, see 
* For example, if the (sandbox) store name is: teststore--admin then the web project store id is: teststore *
    * Note: Although the staging sandbox store name is currently equivalent to the web project store id, it should
    * be derived using 'buildStagingStoreName'.
    * 
    * @param storeName the sandbox store id
    * 
    * @return the web project store id
    */
   public static String getWebProjectStoreId(final String storeName)
   {
      final int index = storeName.indexOf(WCMUtil.STORE_SEPARATOR);
      return (index == -1
              ? storeName
              : storeName.substring(0, index));
   }
   
   /**
    * Extracts the web project store id from the avm path
    *
    * For example, if the avm path is: teststore--admin:/www/ROOT then the web project id is: teststore
    *
    * @param avmPath an absolute avm path
    * 
    * @return the web project store id.
    */
   public static String getWebProjectStoreIdFromPath(final String avmPath)
   {
       return getWebProjectStoreId(getStoreName(avmPath));
   }
   /**
    * Indicates whether the store name describes a preview store.
    *
    * @param storeName the store name
    * 
    * @return true if the store is a preview store, false otherwise.
    */
   protected static boolean isPreviewStore(final String storeName)
   {
      return ((storeName != null) && (storeName.endsWith(WCMUtil.STORE_SEPARATOR + WCMUtil.STORE_PREVIEW)));
   }
   
   
   /**
    * http://wiki.alfresco.com/wiki/WCM_Deployment_Features#Debugging_.26_Testing
    *
    * Examples of locally deployed store names for web project "MyWebProj" are:
    *
    *    MyWebProjlive
    *    MyWebProj--adminlive
    *
    * Note: if web project "MyWebProjlive" is pre-created then should be possible to browse staging:
    *
    *    http://wiki.alfresco.com/wiki/WCM_Deployment_Features#Deployed_Runtime
    *
    * @param storeName
    * @return
    */
   protected static boolean isLocalhostDeployedStore(String wpStoreId, String storeName)
   {
      return ((storeName.startsWith(wpStoreId)) &&
              (storeName.endsWith(AVMDeployWebsiteAction.LIVE_SUFFIX)) &&
              (! wpStoreId.endsWith(AVMDeployWebsiteAction.LIVE_SUFFIX)));
   }
   /**
    * Indicates whether the store name describes a workflow store.
    *
    * @param storeName the store name
    * 
    * @return true if the store is a workflow store, false otherwise.
    */
   protected static boolean isWorkflowStore(String storeName)
   {
      if (WCMUtil.isPreviewStore(storeName))
      {
         storeName = WCMUtil.getCorrespondingMainStoreName(storeName);
      }
      
      return ((storeName != null) && (storeName.indexOf(STORE_SEPARATOR + STORE_WORKFLOW) != -1));
   }
   
   /**
    * Indicates whether the store name describes a user store.
    *
    * @param storeName the store name
    * 
    * @return true if the store is a user store, false otherwise.
    */
   public static boolean isUserStore(String storeName)
   {
      if (WCMUtil.isPreviewStore(storeName))
      {
         storeName = WCMUtil.getCorrespondingMainStoreName(storeName);
      }
      return ((storeName != null) && (storeName.indexOf(WCMUtil.STORE_SEPARATOR) != -1));
   }
   
   /**
    * Indicates whether the store name describes a staging store.
    * 
    * @param storeName the store name
    * 
    * @return true if the store is a main store, false otherwise.
    */
   public static boolean isStagingStore(String storeName)
   {
      return ((storeName != null) && (storeName.indexOf(WCMUtil.STORE_SEPARATOR) == -1));
   }
   /**
    * Extracts the username from the store name.
    *
    * @param storeName the store name
    * 
    * @return the username associated or null if this is a staging store.
    */
   public static String getUserName(String storeName)
   {
      if (WCMUtil.isPreviewStore(storeName))
      {
         storeName = WCMUtil.getCorrespondingMainStoreName(storeName);
      }
      final int index = storeName.indexOf(WCMUtil.STORE_SEPARATOR);
      return (index == -1 ? null : unescapeStoreNameComponent(storeName.substring(index
            + WCMUtil.STORE_SEPARATOR.length())));
   }
   
   /**
    * Extracts the workflow id
    * 
    * @param storeName
    * @return
    */
   public static String getWorkflowId(String storeName)
   {
      if (WCMUtil.isPreviewStore(storeName))
      {
         storeName = WCMUtil.getCorrespondingMainStoreName(storeName);
      }
      final int index = storeName.indexOf(STORE_SEPARATOR + STORE_WORKFLOW);
      return (index == -1
              ? null
              : storeName.substring(index + WCMUtil.STORE_SEPARATOR.length()));
   }
   /**
    * Returns the corresponding main store name if this is a preview store name.
    *
    * @param storeName the preview store name.
    * 
    * @return the corresponding main store name.
    * 
    * @exception IllegalArgumentException if this is not a preview store name.
    */
   protected static String getCorrespondingMainStoreName(final String storeName)
   {
      if (!WCMUtil.isPreviewStore(storeName))
      {
         throw new IllegalArgumentException("store " + storeName + " is not a preview store");
      }
      return storeName.substring(0, 
                                 (storeName.length() - 
                                  (WCMUtil.STORE_SEPARATOR + WCMUtil.STORE_PREVIEW).length()));
   }
   /**
    * Returns the corresponding preview store name if this is a main store name.
    *
    * @param storeName the main store name.
    * 
    * @return the corresponding preview store name.
    * 
    * @exception IllegalArgumentException if this is not a main store name.
    */
   protected static String getCorrespondingPreviewStoreName(final String storeName)
   {
      if (WCMUtil.isPreviewStore(storeName))
      {
         throw new IllegalArgumentException("store " + storeName + " is already a preview store");
      }
      return storeName + WCMUtil.STORE_SEPARATOR + WCMUtil.STORE_PREVIEW;
   }
   /**
    * Returns the corresponding path in the main store name if this is a path in 
    * a preview store.
    *
    * @param avmPath an avm path within the main store.
    * 
    * @return the corresponding path within the preview store.
    * 
    * @exception IllegalArgumentException if this is not a path within the preview store.
    */
   protected static String getCorrespondingPathInMainStore(final String avmPath)
   {
      String storeName = getStoreName(avmPath);
      storeName = WCMUtil.getCorrespondingMainStoreName(storeName);
      return WCMUtil.getCorrespondingPath(avmPath, storeName);
   }
   /**
    * Returns the corresponding path in the preview store name if this is a path in 
    * a main store.
    *
    * @param avmPath an avm path within the main store.
    * 
    * @return the corresponding path within the preview store.
    * 
    * @exception IllegalArgumentException if this is not a path within the preview store.
    */
   protected static String getCorrespondingPathInPreviewStore(final String avmPath)
   {
      String storeName = getStoreName(avmPath);
      storeName = WCMUtil.getCorrespondingPreviewStoreName(storeName);
      return WCMUtil.getCorrespondingPath(avmPath, storeName);
   }
   /**
    * Returns the corresponding path in the store provided.
    * 
    * @param avmPath an avm path
    * @param otherStore the other store name to return the corresponding path for
    * 
    * @return the corresponding path within the supplied store
    */
   public static String getCorrespondingPath(final String avmPath, final String otherStoreName)
   {
      return (buildAVMPath(otherStoreName, WCMUtil.getStoreRelativePath(avmPath)));
   }
   
   /**
    * Utility function for escaping part of a compound store name (delimited by STORE_SEPARATOR sequences). Uses ISO
    * 9075 style encoding to escape otherwise problematic character sequences.
    * 
    * @param component
    *           the component
    * @return the escaped string
    */
   public static final String escapeStoreNameComponent(String component)
   {
      StringBuilder builder = null;
      int length = component.length();
      // If the component matches one of the common suffixes, encode it
      if (component.equals(STORE_PREVIEW) || component.equals(STORE_WORKFLOW))
      {
         builder = new StringBuilder(length + 5);
         appendEncoded(builder, component);
         return builder.toString();
      }
      // Look for problematic character sequences
      Matcher matcher = PATTERN_ILLEGAL_SEQUENCE.matcher(component);
      int lastAppendPosition = 0;
      while (matcher.find())
      {
         if (builder == null)
         {
            builder = new StringBuilder(length + 5);
         }
         if (matcher.start() != lastAppendPosition)
         {
            builder.append(component, lastAppendPosition, matcher.start());
         }
         lastAppendPosition = matcher.end();
         appendEncoded(builder, matcher.group());
      }
      if (builder == null)
      {
         return component;
      }
      if (lastAppendPosition < length)
      {
         builder.append(component, lastAppendPosition, length);
      }
      return builder.toString();
   }
   /**
    * Utility function for decoding from Strings produced by the above method.
    * 
    * @param component
    *           the encoded component
    * @return the decoded component
    */
   private static String unescapeStoreNameComponent(String component)
   {
      StringBuilder builder = null;
      int length = component.length();
      int lastAppendPosition = 0;
      int escapeIndex;
      while ((escapeIndex = component.indexOf("-x", lastAppendPosition)) != -1)
      {
         if (builder == null)
         {
            builder = new StringBuilder(length + 5);
         }
         if (escapeIndex != lastAppendPosition)
         {
            builder.append(component, lastAppendPosition, escapeIndex);
         }
         lastAppendPosition = component.indexOf('-', escapeIndex + 2);
         builder.appendCodePoint(Integer.parseInt(component.substring(escapeIndex + 2, lastAppendPosition), 16));
         lastAppendPosition++;
      }
      if (builder == null)
      {
         return component;
      }
      if (lastAppendPosition < length)
      {
         builder.append(component, lastAppendPosition, length);
      }
      return builder.toString();
   }
   private static final void appendEncoded(StringBuilder builder, String sequence)
   {
      builder.append("-x").append(Integer.toString(sequence.codePointAt(0), 16).toUpperCase()).append("-");
      int length = sequence.length();
      int next = sequence.offsetByCodePoints(0, 1);
      if (next < length)
      {
         builder.append(sequence, next, length);
      }
   }
   /**
    * Returns the main staging store name for the specified web project
    * 
    * @param wpStoreId   web project store id to build staging store name for
    * @return String     main staging store name for the specified web project store id
    */
   public static String buildStagingStoreName(final String wpStoreId)
   {
       ParameterCheck.mandatoryString("wpStoreId", wpStoreId);
       return wpStoreId;
   }
   
   /**
    * Returns the preview store name for the specified store id.
    * 
    * @param storeId store id to build preview store name for
    * 
    * @return preview store name for the specified store id
    */
   protected static String buildStagingPreviewStoreName(final String storeId)
   {
      return (WCMUtil.buildStagingStoreName(storeId) + WCMUtil.STORE_SEPARATOR + 
              WCMUtil.STORE_PREVIEW);
   }
   
   /**
    * Returns the user's main store name for a specific username
    * 
    * @param storeId store id to build user store name for
    * @param username of the user to build store name for
    * 
    * @return the main store for the specified user and store id
    */
   public static String buildUserMainStoreName(final String storeId, 
                                               final String userName)
   {
       ParameterCheck.mandatoryString("userName", userName);
       String fixedUserName = escapeStoreNameComponent(userName);
       return (WCMUtil.buildStagingStoreName(storeId) + WCMUtil.STORE_SEPARATOR + 
               fixedUserName);
   }
   
   /**
    * Returns the preview store name for a specific username.
    * 
    * @param storeId store id to build user preview store name for
    * @param username of the user to build preview store name for
    * 
    * @return the preview store for the specified user and store id
    */
   protected static String buildUserPreviewStoreName(final String storeId, 
                                                  final String username)
   {
      return (WCMUtil.buildUserMainStoreName(storeId, username) + WCMUtil.STORE_SEPARATOR + 
              WCMUtil.STORE_PREVIEW);
   }
   /**
    * Returns the store name for a specific workflow Id.
    * 
    * @param storeId store id to build workflow store name for
    * @param workflowId of the user to build workflow store name for
    * 
    * @return the store for the specified workflow and store ids
    */
   protected static String buildWorkflowMainStoreName(final String storeId, 
                                                   final String workflowId)
   {
       ParameterCheck.mandatoryString("workflowId", workflowId);
       return (WCMUtil.buildStagingStoreName(storeId) + WCMUtil.STORE_SEPARATOR +
               workflowId);
   }
   /**
    * Returns the preview store name for a specific workflow Id.
    * 
    * @param storeId store id to build preview workflow store name for
    * @param workflowId of the user to build preview workflow store name for
    * 
    * @return the store for the specified preview workflow and store ids
    */
   protected static String buildWorkflowPreviewStoreName(final String storeId, 
                                                      final String workflowId)
   {
      return (WCMUtil.buildWorkflowMainStoreName(storeId, workflowId) +
              WCMUtil.STORE_SEPARATOR + WCMUtil.STORE_PREVIEW);
   }
   /**
    * Returns the root path for the specified store name
    * 
    * eg. mystore -> mystore:/www
    * 
    * @param storeName store to build root path for
    * 
    * @return root path for the specified store name
    */
   public static String buildStoreRootPath(final String storeName)
   {
       ParameterCheck.mandatoryString("storeName", storeName);
       return buildAVMPath(storeName, AVM_PATH_SEPARATOR_CHAR + JNDIConstants.DIR_DEFAULT_WWW);
   }
   /**
    * Returns the root path for the specified sandbox name
    * 
    * * eg. mystore -> mystore:/www/avm_webapps
    * 
    * @param storeName store to build root sandbox path for
    * 
    * @return root sandbox path for the specified store name
    */
   public static String buildSandboxRootPath(final String storeName)
   {
       ParameterCheck.mandatoryString("storeName", storeName);
       return buildAVMPath(storeName, JNDIConstants.DIR_DEFAULT_WWW_APPBASE);
   }
   
   /**
    * Returns the root webapp path for the specified store and webapp name
    * 
    * @param storeName store to build root webapp path for
    * @param webapp webapp folder name
    * 
    * @return the root webapp path for the specified store and webapp name
    */
   public static String buildStoreWebappPath(final String storeName, String webApp)
   {
       ParameterCheck.mandatoryString("webApp", webApp);
       return WCMUtil.buildSandboxRootPath(storeName) + AVM_PATH_SEPARATOR_CHAR + webApp;
   }
   
   public static String lookupStoreDNS(AVMService avmService, String store)
   {
       ParameterCheck.mandatoryString("store", store);
       
       final Map