#!/usr/bin/env python

'''
The application is a starship sales site. We are wealthy spacefarers shopping
for a new ship. We want to search for starships, sort them by cost, and filter
them by cost (if we have a starship budget we don't want to look at ships above
it.)

If there are pilots associated with the starship, we want to get more
information about them as well, because we are concerned about previous owners.

INSTALLATION:
=============

Tested with
    Python 2.7.10 on Linux

Make sure that "swapi" (https://swapi-python.readthedocs.org/en/latest/readme.html#installation) is installed
    $ pip install swapi

Install Flask, A lightweight Python web framework (http://flask.pocoo.org/)
    $ pip install Flask

To run it, just type:
    $ ./starshipsales

and you can access it at port 5000
'''
from flask import Flask, render_template, request
import swapi
import re

app = Flask(__name__)

print ("\n[INFO] Please wait while I load some data.")
print ("[INFO] This may take a while, depending on your system...\n")

# Load data
print ("[INFO] Loading starships...")
all_starships_info = swapi.get_all("starships")
starships_names = [starship.name for starship in all_starships_info.iter()]

starships_and_prices = {}
for ship in all_starships_info.iter():
    if str(ship.cost_in_credits) != 'unknown':
        starships_and_prices[int(ship.cost_in_credits)] = str(ship.name)

print ("[INFO] Matching ships to pilots...")
ship_pilot = {}
for ship in all_starships_info.iter():
    if ship.get_pilots().count() >= 1:
        for pilot in ship.get_pilots().iter():
            ship_pilot.setdefault(ship.name.encode('utf-8'), []).append(pilot.name.encode('utf-8'))

print ("[INFO] Matching ships to films...\n")
ship_film = {}
for ship in all_starships_info.iter():
    if ship.get_films().count() >= 1:
        for film in ship.get_films().iter():
            ship_film.setdefault(ship.name.encode('utf-8'), []).append(film.title.encode('utf-8'))

print ("[INFO] All data loaded... You can start using the webapp\n")


# The main features of the app are, from most important to least, are:
@app.route("/")
def index():
    return render_template('index.html')


# [ 0. See a list of all starships ]
@app.route("/starships")
def get_all_starships():
    return render_template('starships.html', starships_names=starships_names)


# [ 0. See individual starship ]
@app.route("/<starship_name>")
def starships_info(starship_name):
    return render_template('starshipinfo.html', starship_name=starship_name, starshipnames=all_starships_info.iter(), starshipinfos=all_starships_info.iter(), ship_pilot=ship_pilot, ship_film=ship_film)


# [ 0. Search list by ship name ]
@app.route("/search")
def search():
    # Get user input
    return render_template('search.html')


@app.route("/search", methods=['POST'])
def search_result():
    # Search through the list
    search_starship = re.compile(request.form['text'])
    search_results = filter(search_starship.search, starships_names)
    search_count = len(search_results)
    return render_template('search_results.html', search_results=search_results, search_count=search_count)


# [ 0. Sort list by price ]
@app.route("/prices")
def sort_list_by_price():
    return render_template('prices.html', starships_and_prices=starships_and_prices)


# [ 0. Filter list by price ]
@app.route("/pricerange")
def searchprice():
    return render_template('pricerange.html')


@app.route("/pricerange", methods=['POST'])
def filter_by_price():
    if request.form['text'] == "":
        user_input = 0
    else:
        user_input = request.form['text']

    filter_results = dict((key, value) for key, value in starships_and_prices.iteritems() if key <= int(user_input))
    search_count = len(filter_results)
    price_range = request.form['text']
    return render_template('pricerange_results.html', filter_results=filter_results, search_count=search_count, price_range=price_range)


# [ 0. See info on pilots attached to individual starships ]
@app.route("/pilots")
def pilots_of_ships():
    return render_template('pilots.html', ship_pilot=ship_pilot)


if __name__ == "__main__":
    app.debug = True
    app.run(host='0.0.0.0')
