#!/usr/bin/w3tclsh
#
# This script demonstrates how W3 to return resources (such as
# an image) held in separate files or in a separate SQLite database.
#
package require w3

# Common header and footer.
proc common-header {} {
  w3-trim {
    <html>
    <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <link href="%url([w3-param SCRIPT_NAME]/style.css)" rel="stylesheet">
    <title>W3 External Content Demo</title>
    </head>
    <body>
  }
}
proc common-footer {} {
  w3-trim {
    </body>
    </html>
  }
}

# The style sheet
proc w3-page-style.css {} {
  w3-mimetype text/css
  w3-cache-control max-age=3600
  w3-trim {
    pre {
       border: 1px solid black;
       padding: 1ex;
    }
  }
}

# This is the default page
proc w3-default {} {
  common-header
  w3-trim {
    <h1>External Content Demo</h1>
    <p>This demo shows how W3 can return resources (such as images)
    that are loaded from separate files on disk, or from a separate
    database.  This demo shows two images:

    <p><img src="image1"><br>"plume1"
    <p><img src="image2"><br>"plume2"

    <p>Both images are the same PNG file.  The first image is loaded
    from a separate file on disk.  The second image is loaded form
    an SQLite database.

    <p>Click <a href="self">here</a> to see the complete W3 script
    that generates this application.
  }
}

# The /self page that returns HTML that displays a copy of this script itself
proc w3-page-self {} {
  w3-cache-control max-age=3600
  common-header
  set fd [open [w3-param SCRIPT_FILENAME] rb]
  set script [read $fd]
  close $fd
  w3-trim {
    <h1>Text Of The External Content Demo Script</h1>
    <pre>%html($script)</pre>
  }
  common-footer
}

# The /image1 image, read from a separate file named "plume.png"
# found in the same directory as this script.
#
proc w3-page-image1 {} {
  w3-mimetype image/png
  set filename [file dir [w3-param SCRIPT_FILENAME]]/plume.png
  set fd [open $filename rb]
  w3 [read $fd]
  close $fd
}

# The /image2 image, read from an SQLite database named "plume.db"
# found in the same directory as this script.
#
proc w3-page-image2 {} {
  set dbname [file dir [w3-param SCRIPT_FILENAME]]/plume.db
  sqlite3 db $dbname
  db eval {SELECT data, mimetype FROM image LIMIT 1} break
  w3-mimetype $mimetype
  w3 $data
  db close
}

# Start W3 running
w3-start $argv
