#!./tclsh
# $Id: import 391 2007-01-25 03:53:59Z mikes@u.washington.edu $
# ========================================================================
# Copyright 2008 University of Washington
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# ========================================================================

#  import
#
#  Purpose:  CGI script that generates a page displaying a message
#            list of the indicated folder. 
#
#  Input:    PATH_INFO: [/<col_number>]/<directory_path>
#            along with possible search parameters:
set import_args {
}

# inherit global config
source ../alpine.tcl

# TEST
proc cgi_suffix {args} {
  return ""
}

WPEval $import_args {

  # grok PATH_INFO for collection 'c' and folder path 'p'
  if {!([info exists env(PATH_INFO)] && [string length $env(PATH_INFO)]
       && [regexp {^/([0-9]+)/(.*)$} $env(PATH_INFO) dummy c p])} {
    WPCmd PEInfo statmsg "Invalid Detach: $env(SCRIPT_NAME)"
    cgi_exit
  }

  if {[catch {WPImport file "Missing File Upload"} result] == 0} {
    set local_file [lindex $file 0]
    if {[catch {WPImport newFolder "import name"} result] == 0} {
      set iname [string trim $newFolder]
      if {[string length $iname]} {
	set fldr [eval "file join $p $iname"]
	if {[catch {WPCmd PEFolder import $local_file $c $fldr} result] == 0} {
	  WPCmd PEInfo statmsg "Imported folder $iname"
	} else {
	  WPCmd PEInfo statmsg "Can't Import File: $result"
	}
      } else {
	WPCmd PEInfo statmsg "Must provide uploaded folder name"
      }
    } else {
      WPCmd PEInfo statmsg "No Import Folder Name: $result"
    }

    catch {file delete -force $local_file}
  } else {
    WPCmd PEInfo statmsg "Cannot Import: $result"
  }

  cgi_html {
    cgi_head {
      cgi_javascript {
	cgi_puts "window.parent.hideLoading();"
	cgi_puts "window.parent.redrawFolderList();"
      }
    }
    cgi_body {}
  }
}
