
from PIL import Image
import json
import sys
import os
import argparse

p = argparse.ArgumentParser (description="generate multires pannellum")
p.add_argument ('imagefile',  help='image file')
p.add_argument ('--title',    help='image title', required=True)
p.add_argument ('--bottom',   help='bottom of image is this many degrees up from nadir', default=0, type=int)

args = p.parse_args()

im = Image.open (args.imagefile)
print im.size
# the image needs to be a full sphere, so fill out its size to 2x*x .
w, h = im.size
x = w/2
im0 = Image.new ('RGB', (2 * x, x))


if args.bottom == 0:
    # default case for quadcopter (which includes the nadir).
    im0.paste (im, (0, x - h))
else:
    # the full sweep from nadir to zenith is 180 degrees.
    # 90 degrees would mean the bottom is at x/2.
    # 45 degrees is x/4.
    # top                        bot
    # [---XXXXXXXXXXXXX------------] 90: x - x/2 - h
    # [-----------XXXXXXXXXXXX-----] 45: x - x/4 - h
    m = 180.0 / args.bottom
    v = x - (x / m) - h
    assert v >= 0
    im0.paste (im, (0, int(v)))

base, ext = os.path.splitext (args.imagefile)

path = base + '_sphere' + ext
im0.save (path)

os.system ('python /home/rushing/src/pannellum-2.2.1/utils/multires/generate.py %s' % (path,))
config = json.loads (open ('output/config.json', 'rb').read())
config['multiRes']['path'] = 'output/' + config['multiRes']['path']
config['multiRes']['fallbackPath'] = 'output/' + config['multiRes']['fallbackPath']
config['pitch'] = -20
config['hfov'] = 90
config['autoLoad'] = True
config['autoRotate'] = -1

template = """
<!DOCTYPE HTML>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>%s</title>
    <link rel="stylesheet" href="https://cdn.pannellum.org/2.2/pannellum.css"/>
    <script type="text/javascript" src="https://cdn.pannellum.org/2.2/pannellum.js"></script>
    <style>
      #panorama {
      width: 100%%;
      height: 700px;
      }
    </style>
  </head>
  <body>
    <div id="panorama"></div>
    <script>
      pannellum.viewer('panorama', %s);
    </script>
    </div>
  </body>
  </html>
"""

open ('index.html', 'wb').write (template % (args.title, json.dumps (config, sort_keys=True, indent=4)))

