package org.basex.http.webdav;

import javax.servlet.http.*;

import org.basex.http.*;
import org.basex.http.webdav.impl.*;
import org.basex.server.*;
import org.basex.util.*;

import com.bradmcevoy.common.*;
import com.bradmcevoy.http.*;

/**
 * WebDAV resource factory. Main class for generating WebDAV resources.
 *
 * @author BaseX Team 2005-15, BSD License
 * @author Rositsa Shadura
 * @author Dimitar Popov
 */
final class BXResourceFactory implements ResourceFactory,
    ResourceMetaDataFactory<BXAbstractResource> {

  /** Thread local variable to hold the current context. */
  private static final ThreadLocal<HTTPContext> CONTEXTS = new ThreadLocal<>();

  /** WebDAV service. */
  private WebDAVService<BXAbstractResource> service;

  /**
   * Creates a new service.
   * @param http http context
   */
  void init(final HTTPContext http) {
    service = new WebDAVService<>(this, http);
    CONTEXTS.set(http);
  }

  /**
   * Closes the database session.
   */
  void close() {
    service.close();
    CONTEXTS.remove();
  }

  @Override
  public Resource getResource(final String host, final String dbpath) {
    try {
      final HttpServletRequest r = CONTEXTS.get().req;
      Path p = Path.path(dbpath);
      if(!r.getContextPath().isEmpty()) p = p.getStripFirst();
      if(!r.getServletPath().isEmpty()) p = p.getStripFirst();
      if(p.isRoot()) return new BXRoot(service);

      final String db = p.getFirst();
      return p.getLength() == 1 ?
        service.dbExists(db) ?
          new BXDatabase(new ResourceMetaData(db, service.timestamp(db)), service) :
          null :
        service.resource(db, p.getStripFirst().toString());
    } catch(final LoginException ex) {
      return BXNotAuthorizedResource.NOAUTH;
    } catch(final Exception ex) {
      Util.errln(ex);
    }
    return null;
  }

  @Override
  public BXFile file(final WebDAVService<BXAbstractResource> s, final ResourceMetaData d) {
    return new BXFile(d, s);
  }

  @Override
  public BXFolder folder(final WebDAVService<BXAbstractResource> s, final ResourceMetaData d) {
    return new BXFolder(d, s);
  }

  @Override
  public BXDatabase database(final WebDAVService<BXAbstractResource> s, final ResourceMetaData d) {
    return new BXDatabase(d, s);
  }
}
