text: 'use strict';
  
  require('dotenv').config();
  
  //-- Application Dependancies--//
  const express = require('express');
  const path = require('path');
  const cors = require('cors');
  const superagent = require('superagent');
  const methodOverride = require('method-override');
  const pg = require('pg');
  
  //-- Application Setup --//
  const app = express();
  const PORT = process.env.PORT || 3000;
  app.use(cors());
  
  //-- Configure Database --//
  const client = new pg.Client(process.env.DATABASE_URL);
  client.connect();
  client.on('error', err => console.error(err));
  
  //-- Application Middeware --//
  app.use(express.urlencoded({extended:true}));
  app.use('/public', express.static('public'));
  
  //-- Set View Engine for templating --//
  app.set('views', path.join(__dirname, 'views/pages'));
  app.set('view engine', 'ejs');
  
  // Middleware to handle PUT and DELETE
  app.use(methodOverride((request, response) => {
    if (request.body && typeof request.body === 'object' && '_method' in request.body) {
      // look in urlencoded POST bodies and delete it
      let method = request.body._method;
      delete request.body._method;
      return method;
    }
  }))
  
  //-- API Routes --//
  app.get('/', getBooks) //define route to get all books
  app.get('/searches/', searchBooks);
  app.post('/searches/new', newSearch);
  app.post('/books', createBook);
  app.get('/books/:id', getOneBook);
  app.put('/books/:id', updateBook);
  app.delete('/books/:id', deleteBook);
  
  //-- Catch all --//
  app.get('*', (request, response) => response.status(404).send('This route does not exist'));
  
  app.listen(PORT, () => console.log(`Listening on port: ${PORT}`));
  
  //-- Helper Functions --//
  function searchBooks(request, response) {
    response.render('searches/new');
  }
  
  function handleError(error, response){
    response.render('error', {error: error});
  }
  
  // Constructor
  function Books(book){
    const placeholderImage = 'https://i.imgur.com/J5LVHEL.jpg';
    let httpRegex = /^(http:\/\/)/g;
  
    this.title = book.title || 'No Title Availbale';
    this.author = book.authors || 'No Author Available';
    this.description = book.description || 'No Description Available';
    this.image_url = book.imageLinks ? book.imageLinks.smallThumbnail.replace(httpRegex, 'https://') : placeholderImage;
    this.isbn = book.industryIdentifiers ? `ISBN 13 ${(book.industryIdentifiers[0].identifier)}` : 'No ISBN available';
    this.id = book.industryIdentifiers ? `${(book.industryIdentifiers[0].identifiers)}` : '';
  }
  
  function newSearch(request, response){
    let url = `https://www.googleapis.com/books/v1/volumes?q=`;
  
  
    if(request.body.search[1] === 'title') {url += `+intitle:${request.body.search[0]}`;}
    if(request.body.search[1] === 'author') {url += `+inauthor:${request.body.search[0]}`;}
  
    return superagent.get(url)
      .then(result => result.body.items.map(data => new Books(data.volumeInfo)))
      .then(result => response.render('searches/show', {searchResults: result}))
      .catch((error) => handleError(error, response));
  }
  
  function getBooks(request, response){
    let SQL = `SELECT * FROM books`;
  
    return client.query(SQL)
      .then(result => {
        if(result.rows.rowCount === 0){
          response.render('searches/new')
        }else{
          response.render('index', {DBresults: result.rows})
        }
      })
      .catch(err => console.error(err));
  }
  
  function createBook(request, response){
    let normalBookshelf = request.body.bookshelf.toLowerCase();
  
    let {title, author, description, image_url, isbn} = request.body;
  
    let SQL = `INSERT INTO books (title, author, description, image_url, isbn, bookshelf) VALUES($1, $2, $3, $4, $5, $6) RETURNING id;`;
    let values = [title, author, description, image_url, isbn, normalBookshelf];
  
    return client.query(SQL, values)
      .then(result => {
        response.redirect(`/books/${result.rows[0].id}`)
      })
      .catch(err => console.error(err));
  }
  
  function getOneBook(request, response){
    getBookShelves()
      .then(shelves => {
        let SQL = `SELECT * FROM books WHERE id=$1;`;
        let values = [request.params.id];
        client.query(SQL, values)
          .then(result => {
            response.render('books/show', {book: result.rows[0], bookshelves: shelves.rows})
          })
          .catch(err => console.error('here', err));
      })
  }
  
  function getBookShelves(){
    let SQL = 'SELECT DISTINCT bookshelf FROM books ORDER BY bookshelf;';
    return client.query(SQL);
  }
  
  function deleteBook(request, response){
    let SQL = `DELETE FROM books WHERE id=$1;`;
    let values = [request.params.id];
  
    return client.query(SQL, values)
      .then(response.redirect('/'))
      .catch(handleError);
  }
  
  function updateBook(request, response){
    let {title, author, description, image_url, isbn, bookshelf} = request.body;
  
    let SQL = `UPDATE books SET title=$1, author=$2, description=$3, image_url=$4, isbn=$5, bookshelf=$6  WHERE id=$7;`;
    let values = [title, author, description, image_url, isbn, bookshelf, request.params.id];
  
    client.query(SQL, values)
      .then(response.redirect(`/books/${request.params.id}`))
      .catch(handleError);
  }
  
  
  