#----------------------------------------------------------------------------#
# Imports
#----------------------------------------------------------------------------#

import json
import dateutil.parser
import babel
from flask import Flask, render_template, request, Response, flash, redirect, url_for, jsonify, make_response
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from sqlalchemy import func
import logging
from logging import Formatter, FileHandler
from flask_wtf import Form
from forms import *
from datetime import datetime
import sys
#----------------------------------------------------------------------------#
# App Config.
#----------------------------------------------------------------------------#

app = Flask(__name__)
moment = Moment(app)
app.config.from_object('config')
db = SQLAlchemy(app)

#  connect to a local postgresql database
migrate = Migrate(app, db)


#----------------------------------------------------------------------------#
# Models.
#----------------------------------------------------------------------------#

class Venue(db.Model):
    __tablename__ = 'Venue'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    city = db.Column(db.String(120))
    state = db.Column(db.String(120))
    address = db.Column(db.String(120))
    phone = db.Column(db.String(120))
    website = db.Column(db.String(120))
    image_link = db.Column(db.String(500))
    facebook_link = db.Column(db.String(120))
    
    # TODO: implement any missing fields, as a database migration using Flask-Migrate
    # back_popultes Show.venue
    website = db.Column(db.String(120))
    genres = db.relationship('VenueGenres', backref='Venue', cascade='all, delete-orphan', lazy=True)
    artists = db.relationship("Show", back_populates="venue")


    def __repr__(self):
      return f'<Venue {self.id} "{self.name}" [c: {self.city} s:{self.state}]>'


class Artist(db.Model):
    __tablename__ = 'Artist'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    city = db.Column(db.String(120))
    state = db.Column(db.String(120))
    phone = db.Column(db.String(120))
    #genres = db.Column(db.String(120))
    image_link = db.Column(db.String(500))
    facebook_link = db.Column(db.String(120))

    # TODO: implement any missing fields, as a database migration using Flask-Migrate
    # back_popultes Show.artist
    genres = db.relationship('ArtistGenres', backref='Artist', cascade='all, delete-orphan', lazy=True)
    website = db.Column(db.String(120))
    venues = db.relationship("Show", back_populates="artist")

    def __repr__(self):
      return f'<Artist {self.id} "{self.name}">'

# TODO Implement Show and Artist models, and complete all model relationships and properties, as a database migration.


class Show(db.Model):
  __tablename__ = "Show"

  venue_id = db.Column(db.Integer, db.ForeignKey('Venue.id'), primary_key=True)
  artist_id = db.Column(db.Integer, db.ForeignKey('Artist.id'), primary_key=True)

  start_time = db.Column(db.DateTime(), primary_key=True)
  artist = db.relationship("Artist", back_populates="venues")
  venue = db.relationship("Venue", back_populates="artists")
  
  def __repr__(self):
    return f'<Show {self.start_time} [v:{self.venue_id} a:{self.artist_id}]>'


class VenueGenres(db.Model):
  __tablename__ = "Venue_Genres"

  id = db.Column(db.Integer, primary_key=True)
  genre = db.Column(db.String(120))
  venue_id = db.Column(db.Integer, db.ForeignKey('Venue.id'), nullable=False)

  def __repr__(self):
    return f'<VenueGenre {self.id} {self.name} venue:{self.venue_id}>'


class ArtistGenres(db.Model):
  __tablename__ = "Artist_Genres"

  id = db.Column(db.Integer, primary_key=True)
  genre = db.Column(db.String(120))
  artist_id = db.Column(db.Integer, db.ForeignKey('Artist.id'), nullable=False)

  def __repr__(self):
    return f'<ArtistGenre {self.id} {self.name} venue:{self.artist_id}>'


#----------------------------------------------------------------------------#
# Filters.
#----------------------------------------------------------------------------#

def format_datetime(value, format='medium'):
  date = dateutil.parser.parse(value)
  if format == 'full':
      format="EEEE MMMM, d, y 'at' h:mma"
  elif format == 'medium':
      format="EE MM, dd, y h:mma"
  return babel.dates.format_datetime(date, format)

app.jinja_env.filters['datetime'] = format_datetime

#----------------------------------------------------------------------------#
# Controllers.
#----------------------------------------------------------------------------#

@app.route('/')
def index():
  return render_template('pages/home.html')


#  Venues
#  ----------------------------------------------------------------

@app.route('/venues')
def venues():
  # replace with real venues data.
  # num_shows should be aggregated based on number of upcoming shows per venue.
  """
  # DUMMY
  data=[{
    "city": "San Francisco",
    "state": "CA",
    "venues": [{
      "id": 1,
      "name": "The Musical Hop",
      "num_upcoming_shows": 0,
    }, {
      "id": 3,
      "name": "Park Square Live Music & Coffee",
      "num_upcoming_shows": 1,
    }]
  }, {
    "city": "New York",
    "state": "NY",
    "venues": [{
      "id": 2,
      "name": "The Dueling Pianos Bar",
      "num_upcoming_shows": 0,
    }]
  }]
  """

  states = Venue.query\
    .distinct(Venue.state)\
    .order_by(Venue.state)\
    .all()

  print("========")
  print("Estados -------------")
  print(states)
  print("")

  data2 = []

  for currentState in states:
    cities = Venue.query\
      .filter(Venue.state == currentState.state)\
      .distinct(Venue.city)\
      .order_by(Venue.city)\
      .all()

    print("Ciudades ------------- ", currentState.state, " [" ,len(cities), "]")
    print(cities)
    for currentCity in cities:
      localVenues = []
      content = {}
      content["state"] = currentState.state
      content["city"] = currentCity.city
      content["venues"] = None
      venues = Venue.query\
        .filter(Venue.state == currentState.state)\
        .filter(Venue.city == currentCity.city)\
        .order_by(Venue.id)\
        .all()
      
      print("Localidad ------------- ", currentCity.city, " ", currentCity.state, " [" ,len(venues), "]") 
      print(venues)
      
      for currentVenue in venues:
        dataVenue = {}
        dataVenue["id"] = currentVenue.id
        dataVenue["name"] = currentVenue.name
        dataVenue["num_upcoming_shows"] =  \
          Show.query.join(Venue).join(Artist)\
            .filter(Show.venue_id == Venue.id)\
            .filter(Show.artist_id == Artist.id)\
            .filter(Show.venue_id == currentVenue.id)\
            .filter(Show.start_time >= datetime.now())\
            .count() 
        localVenues.append(dataVenue)
        print(" >>> venue agregado")

      content["venues"] = localVenues
      print("<<<<<< <<<<< <<<<< <<<<< <<<<")
      print("<<<<<< <<<<< <<<<< <<<<< <<<<")

      data2.append(content)
    print("  >> estado, ciudad agregado | localidades [", len(content["venues"]), "]")
  
  print('Data *****  [', len(data2), "]" )
  print(data2)


  return render_template('pages/venues.html', areas=data2)


@app.route('/venues/search', methods=['POST'])
def search_venues():
  # implement search on artists with partial string search. Ensure it is case-insensitive.
  # seach for Hop should return "The Musical Hop".
  # search for "Music" should return "The Musical Hop" and "Park Square Live Music & Coffee"
  """
  response={
    "count": 1,
    "data": [{
      "id": 2,
      "name": "The Dueling Pianos Bar",
      "num_upcoming_shows": 0,
    }]
  }
  """

  response = {}

  search_item = request.form["search_term"].strip().lower()
  search_item = "%{}%".format(search_item)
  venues = Venue.query.filter(func.lower(Venue.name).like(search_item)).all()
  print("Localidades encontradas para '", search_item, "'")
  print(venues)

  response["count"] = len(venues)
  data = []
  for venue in venues:
    content = {}
    content["id"] = venue.id
    content["name"] = venue.name
    content["num_upcoming_shows"] = \
      Show.query.join(Venue).join(Artist)\
        .filter(Show.venue_id == Venue.id)\
        .filter(Show.artist_id == Artist.id)\
        .filter(Show.venue_id == venue.id)\
        .filter(Show.start_time >= datetime.now())\
        .count() 
    data.append(content)
  response["data"] = data

  return render_template('pages/search_venues.html', results=response, search_term=request.form.get('search_term', ''))

@app.route('/venues/<int:venue_id>')
def show_venue(venue_id):
  # shows the venue page with the given venue_id
  # replace with real venue data from the venues table, using venue_id
  """
  data1={
    "id": 1,
    "name": "The Musical Hop",
    "genres": ["Jazz", "Reggae", "Swing", "Classical", "Folk"],
    "address": "1015 Folsom Street",
    "city": "San Francisco",
    "state": "CA",
    "phone": "123-123-1234",
    "website": "https://www.themusicalhop.com",
    "facebook_link": "https://www.facebook.com/TheMusicalHop",
    "seeking_talent": True,
    "seeking_description": "We are on the lookout for a local artist to play every two weeks. Please call us.",
    "image_link": "https://images.unsplash.com/photo-1543900694-133f37abaaa5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=400&q=60",
    "past_shows": [{
      "artist_id": 4,
      "artist_name": "Guns N Petals",
      "artist_image_link": "https://images.unsplash.com/photo-1549213783-8284d0336c4f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=300&q=80",
      "start_time": "2019-05-21T21:30:00.000Z"
    }],
    "upcoming_shows": [],
    "past_shows_count": 1,
    "upcoming_shows_count": 0,
  }
  data2={
    "id": 2,
    "name": "The Dueling Pianos Bar",
    "genres": ["Classical", "R&B", "Hip-Hop"],
    "address": "335 Delancey Street",
    "city": "New York",
    "state": "NY",
    "phone": "914-003-1132",
    "website": "https://www.theduelingpianos.com",
    "facebook_link": "https://www.facebook.com/theduelingpianos",
    "seeking_talent": False,
    "image_link": "https://images.unsplash.com/photo-1497032205916-ac775f0649ae?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80",
    "past_shows": [],
    "upcoming_shows": [],
    "past_shows_count": 0,
    "upcoming_shows_count": 0,
  }
  data3={
    "id": 3,
    "name": "Park Square Live Music & Coffee",
    "genres": ["Rock n Roll", "Jazz", "Classical", "Folk"],
    "address": "34 Whiskey Moore Ave",
    "city": "San Francisco",
    "state": "CA",
    "phone": "415-000-1234",
    "website": "https://www.parksquarelivemusicandcoffee.com",
    "facebook_link": "https://www.facebook.com/ParkSquareLiveMusicAndCoffee",
    "seeking_talent": False,
    "image_link": "https://images.unsplash.com/photo-1485686531765-ba63b07845a7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=747&q=80",
    "past_shows": [{
      "artist_id": 5,
      "artist_name": "Matt Quevedo",
      "artist_image_link": "https://images.unsplash.com/photo-1495223153807-b916f75de8c5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80",
      "start_time": "2019-06-15T23:00:00.000Z"
    }],
    "upcoming_shows": [{
      "artist_id": 6,
      "artist_name": "The Wild Sax Band",
      "artist_image_link": "https://images.unsplash.com/photo-1558369981-f9ca78462e61?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=794&q=80",
      "start_time": "2035-04-01T20:00:00.000Z"
    }, {
      "artist_id": 6,
      "artist_name": "The Wild Sax Band",
      "artist_image_link": "https://images.unsplash.com/photo-1558369981-f9ca78462e61?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=794&q=80",
      "start_time": "2035-04-08T20:00:00.000Z"
    }, {
      "artist_id": 6,
      "artist_name": "The Wild Sax Band",
      "artist_image_link": "https://images.unsplash.com/photo-1558369981-f9ca78462e61?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=794&q=80",
      "start_time": "2035-04-15T20:00:00.000Z"
    }],
    "past_shows_count": 1,
    "upcoming_shows_count": 1,
  }
  data = list(filter(lambda d: d['id'] == venue_id, [data1, data2, data3]))[0]
  """

  venue = Venue.query.get(venue_id)
  
  data = {}
  genres = []
  for g in venue.genres:
    genres.append(g.genre)

  query_shows = Show.query.join(Venue).join(Artist)\
    .filter(Show.venue_id == Venue.id)\
    .filter(Show.artist_id == Artist.id)\
    .filter(Show.venue_id == venue_id)\
    .filter(Show.start_time < datetime.now())\
    .all() 

  past_shows = getShowArtists(query_shows)

  query_shows = Show.query.join(Venue).join(Artist)\
    .filter(Show.venue_id == Venue.id)\
    .filter(Show.artist_id == Artist.id)\
    .filter(Show.venue_id == venue_id)\
    .filter(Show.start_time >= datetime.now())\
    .all()   

  upcoming_shows = getShowArtists(query_shows)

  data["id"] = venue.id
  data["name"] = venue.name
  data["genres"] = genres
  data["address"] = venue.address
  data["city"] = venue.city
  data["state"] = venue.state
  data["phone"] = venue.phone
  data["website"] = venue.website
  data["image_link"] = venue.image_link
  data["facebook_link"] = venue.facebook_link
  data["seeking_talent"] = False # TODO: no está definido en clase venue, va en otro lado? [opcional]
  data["seeking_description"] = "" # TODO: no está definido en clase venue, va en otro lado? [opcional]
  
  data["past_shows"] = past_shows
  data["upcoming_shows"] = upcoming_shows
  data["past_shows_count"] = len(past_shows)
  data["upcoming_shows_count"] = len(upcoming_shows)

  return render_template('pages/show_venue.html', venue=data)


#  Create Venue
#  ----------------------------------------------------------------

@app.route('/venues/create', methods=['GET'])
def create_venue_form():
  form = VenueForm()
  return render_template('forms/new_venue.html', form=form)

@app.route('/venues/create', methods=['POST'])
def create_venue_submission():
  # insert form data as a new Venue record in the db, instead
  #  modify data to be the data object returned from db insertion
  
  form = VenueForm(request.form)
  if request.method == 'POST' and form.validate():

    venue = Venue()
    
    #form.populate_obj(venue)
    venue.name = request.form["name"]
    venue.city = request.form["city"]
    venue.address = request.form["address"]
    venue.state = request.form["state"]
    venue.phone = request.form["phone"]
    if "image_link" in request.form:
      venue.image_link = request.form["image_link"]
    if "website" in request.form:
      venue.website = request.form["website"]
    venue.facebook_link = request.form["facebook_link"]
    
    formGenres = request.form.getlist("genres")
    for genre in formGenres:
      venueGenre = VenueGenres()
      venueGenre.genre = genre
      # Assign genre to venue
      venueGenre.Venue = venue

    print("Venue ", venue)
    print("Forma ", form )
    print("Generos (tam)", len(request.form.getlist("genres")) )
    print("Request ", request.form) 
    
    try:
      db.session.add(venue)
      db.session.commit()

      flash('Venue ' + venue.name + ' was successfully listed!')
    except: 
      db.session.rollback()
      flash('An error occurred. Venue ' + venue.name + ' could not be listed.')
    finally: 
      db.session.close()
  else:
    flash('An error occurred. Venue ' + request.form["name"] + ' failed (validation error).')
    print('Errror: forma no válida')
  
  # on successful db insert, flash success
  #flash('Venue ' + request.form['name'] + ' was successfully listed!')
  #  on unsuccessful db insert, flash an error instead.
  # e.g., flash('An error occurred. Venue ' + data.name + ' could not be listed.')
  # see: http://flask.pocoo.org/docs/1.0/patterns/flashing/
  return render_template('pages/home.html')


@app.route('/venues/<venue_id>', methods=['DELETE'])
def delete_venue(venue_id):
  # Complete this endpoint for taking a venue_id, and using
  # SQLAlchemy ORM to delete a record. Handle cases where the session commit could fail.

  try:
    print('************************')
    print("Borrar ", venue_id)
  
    Show.query.filter_by(venue_id=venue_id).delete()
    VenueGenres.query.filter_by(venue_id=venue_id).delete()
    Venue.query.filter_by(id=venue_id).delete()

    db.session.commit()
    
  except:
    print('xxxxxxxxxxxxxxxx\nNo borré')

    db.session.rollback()
    print(sys.exc_info())

  finally:
    db.session.close()

  return  jsonify({'success': True})
  # BONUS CHALLENGE: Implement a button to delete a Venue on a Venue Page, have it so that
  # clicking that button delete it from the db then redirect the user to the homepage
  #return None


#  Artists
#  ----------------------------------------------------------------
@app.route('/artists')
def artists():
  #  replace with real data returned from querying the database
  """
  data=[{
    "id": 4,
    "name": "Guns N Petals",
  }, {
    "id": 5,
    "name": "Matt Quevedo",
  }, {
    "id": 6,
    "name": "The Wild Sax Band",
  }]
  """
  
  """
  # ###################################
  # IMPORTANTE! Con efecto secundario
  # Agrega un nuevo artista con cada consulta a /artists
  # (cada vez que pasa por aquí)
  # ###################################
  #data = Artist.query.all()
  """
  data = []
  artists = Artist.query.all()

  for artist in artists:
    content = {}
    content["id"] = artist.id
    content["name"] = artist.name
    data.append(content)

  print("Data [", len(data), "] ", data)

  return render_template('pages/artists.html', artists=data)

@app.route('/artists/search', methods=['POST'])
def search_artists():
  # implement search on artists with partial string search. Ensure it is case-insensitive.
  # seach for "A" should return "Guns N Petals", "Matt Quevado", and "The Wild Sax Band".
  # search for "band" should return "The Wild Sax Band".
  """
  response={
    "count": 1,
    "data": [{
      "id": 4,
      "name": "Guns N Petals",
      "num_upcoming_shows": 0,
    }]
  }
  """

  response = {}

  search_item = request.form["search_term"].strip().lower()
  search_item = "%{}%".format(search_item)
  artists = Artist.query.filter(func.lower(Artist.name).like(search_item)).all()
  print("Aritstas encontrados para '", search_item, "'")
  print(artists)

  response["count"] = len(artists)
  data = []
  for artist in artists:
    content = {}
    content["id"] = artist.id
    content["name"] = artist.name
    content["num_upcoming_shows"] = \
      Show.query.join(Venue).join(Artist)\
        .filter(Show.venue_id == Venue.id)\
        .filter(Show.artist_id == Artist.id)\
        .filter(Show.artist_id == artist.id)\
        .filter(Show.start_time >= datetime.now())\
        .count() 
    data.append(content)
  response["data"] = data
  return render_template('pages/search_artists.html', results=response, search_term=request.form.get('search_term', ''))


@app.route('/artists/<int:artist_id>')
def show_artist(artist_id):
  # shows the venue page with the given venue_id
  # replace with real venue data from the venues table, using venue_id
  """
  data1={
    "id": 4,
    "name": "Guns N Petals",
    "genres": ["Rock n Roll"],
    "city": "San Francisco",
    "state": "CA",
    "phone": "326-123-5000",
    "website": "https://www.gunsnpetalsband.com",
    "facebook_link": "https://www.facebook.com/GunsNPetals",
    "seeking_venue": True,
    "seeking_description": "Looking for shows to perform at in the San Francisco Bay Area!",
    "image_link": "https://images.unsplash.com/photo-1549213783-8284d0336c4f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=300&q=80",
    "past_shows": [{
      "venue_id": 1,
      "venue_name": "The Musical Hop",
      "venue_image_link": "https://images.unsplash.com/photo-1543900694-133f37abaaa5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=400&q=60",
      "start_time": "2019-05-21T21:30:00.000Z"
    }],
    "upcoming_shows": [],
    "past_shows_count": 1,
    "upcoming_shows_count": 0,
  }
  data2={
    "id": 5,
    "name": "Matt Quevedo",
    "genres": ["Jazz"],
    "city": "New York",
    "state": "NY",
    "phone": "300-400-5000",
    "facebook_link": "https://www.facebook.com/mattquevedo923251523",
    "seeking_venue": False,
    "image_link": "https://images.unsplash.com/photo-1495223153807-b916f75de8c5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80",
    "past_shows": [{
      "venue_id": 3,
      "venue_name": "Park Square Live Music & Coffee",
      "venue_image_link": "https://images.unsplash.com/photo-1485686531765-ba63b07845a7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=747&q=80",
      "start_time": "2019-06-15T23:00:00.000Z"
    }],
    "upcoming_shows": [],
    "past_shows_count": 1,
    "upcoming_shows_count": 0,
  }
  data3={
    "id": 6,
    "name": "The Wild Sax Band",
    "genres": ["Jazz", "Classical"],
    "city": "San Francisco",
    "state": "CA",
    "phone": "432-325-5432",
    "seeking_venue": False,
    "image_link": "https://images.unsplash.com/photo-1558369981-f9ca78462e61?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=794&q=80",
    "past_shows": [],
    "upcoming_shows": [{
      "venue_id": 3,
      "venue_name": "Park Square Live Music & Coffee",
      "venue_image_link": "https://images.unsplash.com/photo-1485686531765-ba63b07845a7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=747&q=80",
      "start_time": "2035-04-01T20:00:00.000Z"
    }, {
      "venue_id": 3,
      "venue_name": "Park Square Live Music & Coffee",
      "venue_image_link": "https://images.unsplash.com/photo-1485686531765-ba63b07845a7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=747&q=80",
      "start_time": "2035-04-08T20:00:00.000Z"
    }, {
      "venue_id": 3,
      "venue_name": "Park Square Live Music & Coffee",
      "venue_image_link": "https://images.unsplash.com/photo-1485686531765-ba63b07845a7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=747&q=80",
      "start_time": "2035-04-15T20:00:00.000Z"
    }],
    "past_shows_count": 0,
    "upcoming_shows_count": 3,
  }
  data = list(filter(lambda d: d['id'] == artist_id, [data1, data2, data3]))[0]
  """

  artist = Artist.query.get(artist_id)

  data = {}
  genres = []
  for g in artist.genres:
    genres.append(g.genre)

  query_shows = Show.query.join(Venue).join(Artist)\
    .filter(Show.venue_id == Venue.id)\
    .filter(Show.artist_id == Artist.id)\
    .filter(Show.artist_id == artist_id)\
    .filter(Show.start_time < datetime.now())\
    .all() 

  past_shows = getShowVenues(query_shows)

  query_shows = Show.query.join(Venue).join(Artist)\
    .filter(Show.venue_id == Venue.id)\
    .filter(Show.artist_id == Artist.id)\
    .filter(Show.artist_id == artist_id)\
    .filter(Show.start_time >= datetime.now())\
    .all()   

  upcoming_shows = getShowVenues(query_shows)


  data["id"] = artist.id
  data["name"] = artist.name
  data["city"] = artist.city
  data["state"] = artist.state
  data["phone"] = artist.phone
  data["website"] = artist.website 
  data["genres"] = genres
  data["facebook_link"] = artist.facebook_link
  data["seeking_venue"] = False # TODO: no está definido en clase artist, va en otro lado? [campo opcional]
  data["seeking_description"] = "" # TODO: no está definido en clase artist, va en otro lado? [campo opcional]
  data["image_link"] = artist.image_link
  
  data["past_shows"] = past_shows
  data["upcoming_shows"] = upcoming_shows
  data["past_shows_count"] = len(past_shows)
  data["upcoming_shows_count"] = len(upcoming_shows)

  print("Encontrado ", data) 

  return render_template('pages/show_artist.html', artist=data)


#  Update
#  ----------------------------------------------------------------
@app.route('/artists/<int:artist_id>/edit', methods=['GET'])
def edit_artist(artist_id):
  """
  form = ArtistForm()
  artist={
    "id": 4,
    "name": "Guns N Petals",
    "genres": ["Rock n Roll"],
    "city": "San Francisco",
    "state": "CA",
    "phone": "326-123-5000",
    "website": "https://www.gunsnpetalsband.com",
    "facebook_link": "https://www.facebook.com/GunsNPetals",
    "seeking_venue": True,
    "seeking_description": "Looking for shows to perform at in the San Francisco Bay Area!",
    "image_link": "https://images.unsplash.com/photo-1549213783-8284d0336c4f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=300&q=80"
  }
  """
  # populate form with fields from artist with ID <artist_id>
  toUpdate = Artist.query.get(artist_id)
  print("Editar artista ", toUpdate )

  genres = []
  for g in toUpdate.genres:
    genres.append(g.genre)

  artist={
    "id": toUpdate.id,
    "name": toUpdate.name,
    "genres": genres,
    "city": toUpdate.city,
    "state": toUpdate.state,
    "phone": toUpdate.phone,
    "website": toUpdate.website,
    "facebook_link": toUpdate.facebook_link,
    "seeking_talent": False, # TODO: implementar
    "seeking_description": "", # TODO: implementar
    "image_link": toUpdate.image_link
  }

  form = ArtistForm()
  form.name.data = artist["name"]
  form.genres.data = genres 
  form.city.data = artist["city"]
  form.state.data = artist["state"]
  form.phone.data = artist["phone"]
  form.website.data = artist["website"]
  form.facebook_link.data = artist["facebook_link"]
  form.image_link.data = artist["image_link"]
  #form.seeking_talent.data = artist["seeking_talent"]
  #form.seeking_description.data = artist["seeking_description"]

  print("Forma ", form)
  print("Artista ", artist)

  return render_template('forms/edit_artist.html', form=form, artist=artist)


@app.route('/artists/<int:artist_id>/edit', methods=['POST'])
def edit_artist_submission(artist_id):
  # take values from the form submitted, and update existing
  # artist record with ID <artist_id> using the new attributes

  form = ArtistForm(request.form)
  if request.method == 'POST' and form.validate_on_submit():

    artist = Artist.query.get(artist_id)
    ArtistGenres.query.filter_by(artist_id=artist_id).delete()

    artist.name = request.form["name"]
    artist.city = request.form["city"]
    artist.state = request.form["state"]
    artist.phone = request.form["phone"]
    artist.facebook_link = request.form["facebook_link"]
    if "image_link" in request.form:
      artist.image_link = request.form["image_link"]
    if "website" in request.form:
      artist.website = request.form["website"]

    formGenres = request.form.getlist("genres")
    for genre in formGenres:
      artistGenre = ArtistGenres()
      artistGenre.genre = genre
      # Assign genre to artist
      artistGenre.Artist = artist

    print("Artist ", artist)
    print("Forma ", form )
    print("Generos (tam)", len(request.form.getlist("genres")) )
    print("Request ", request.form) 

    
    try:
      db.session.commit()

      flash('Artist ' + artist.name + ' was successfully updated!')
      print('Artista editado')
    except: 
      db.session.rollback()
      flash('An error occurred. Artist ' + artist.name + ' could not be updated.')
      print('Error: Artista no editado')
      print(sys.exc_info())
    finally: 
      db.session.close()
    
  else:
    flash('An error occurred. Artist ' + request.form["name"] + ' failed (validation error).')
    print('Errror: forma no válida')

  return redirect(url_for('show_artist', artist_id=artist_id))


@app.route('/venues/<int:venue_id>/edit', methods=['GET'])
def edit_venue(venue_id):
  """
  form = VenueForm()
  venue={
    "id": 1,
    "name": "The Musical Hop",
    "genres": ["Jazz", "Reggae", "Swing", "Classical", "Folk"],
    "address": "1015 Folsom Street",
    "city": "San Francisco",
    "state": "CA",
    "phone": "123-123-1234",
    "website": "https://www.themusicalhop.com",
    "facebook_link": "https://www.facebook.com/TheMusicalHop",
    "seeking_talent": True,
    "seeking_description": "We are on the lookout for a local artist to play every two weeks. Please call us.",
    "image_link": "https://images.unsplash.com/photo-1543900694-133f37abaaa5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=400&q=60"
  }
  """
  # populate form with values from venue with ID <venue_id>
  toUpdate = Venue.query.get(venue_id)
  print("Editar localidad ", toUpdate )

  genres = []
  for g in toUpdate.genres:
    genres.append(g.genre)

  venue={
    "id": toUpdate.id,
    "name": toUpdate.name,
    "genres": genres,
    "address": toUpdate.address,
    "city": toUpdate.city,
    "state": toUpdate.state,
    "phone": toUpdate.phone,
    "website": toUpdate.website,
    "facebook_link": toUpdate.facebook_link,
    "seeking_talent": False, # TODO: implementar
    "seeking_description": "", # TODO: implementar
    "image_link": toUpdate.image_link
  }

  form = VenueForm()
  form.name.data = venue["name"]
  form.genres.data = genres  
  form.address.data = venue["address"]
  form.city.data = venue["city"]
  form.state.data = venue["state"]
  form.phone.data = venue["phone"]
  form.website.data = venue["website"]  
  form.facebook_link.data = venue["facebook_link"]
  form.image_link.data = venue["image_link"]
  #form.seeking_talent.data = venue["seeking_talent"]
  #form.seeking_description.data = venue["seeking_description"]

  print("Forma ", form)
  print("Localidad ", venue)

  return render_template('forms/edit_venue.html', form=form, venue=venue)


@app.route('/venues/<int:venue_id>/edit', methods=['POST'])
def edit_venue_submission(venue_id):
  # take values from the form submitted, and update existing
  # venue record with ID <venue_id> using the new attributes

  form = VenueForm(request.form)
  if request.method == 'POST' and form.validate_on_submit():

    venue = Venue.query.get(venue_id)
    VenueGenres.query.filter_by(venue_id=venue_id).delete()

    venue.name = request.form["name"]
    venue.city = request.form["city"]
    venue.state = request.form["state"]
    venue.phone = request.form["phone"]
    venue.address = request.form["address"]
    venue.facebook_link = request.form["facebook_link"]
    if "image_link" in request.form:
      venue.image_link = request.form["image_link"]
    if "website" in request.form:
      venue.website = request.form["website"]

    formGenres = request.form.getlist("genres")
    for genre in formGenres:
      venueGenre = VenueGenres()
      venueGenre.genre = genre
      # Assign genre to artist
      venueGenre.Venue = venue

    print("Venue ", venue)
    print("Forma ", form )
    print("Generos (tam)", len(request.form.getlist("genres")) )
    print("Request ", request.form) 

    
    try:
      db.session.commit()

      flash('Venue ' + venue.name + ' was successfully updated!')
      print('Localidad editado')
    except: 
      db.session.rollback()
      flash('An error occurred. Venue ' + venue.name + ' could not be updated.')
      print('Error: Localidad no editado')
      print(sys.exc_info())
    finally: 
      db.session.close()
    
  else:
    flash('An error occurred. Localidad ' + request.form["name"] + ' failed (validation error).')
    print('Errror: forma no válida')

  return redirect(url_for('show_venue', venue_id=venue_id))


#  Create Artist
#  ----------------------------------------------------------------

@app.route('/artists/create', methods=['GET'])
def create_artist_form():
  form = ArtistForm()
  return render_template('forms/new_artist.html', form=form)


@app.route('/artists/create', methods=['POST'])
def create_artist_submission():
  # called upon submitting the new artist listing form
  # insert form data as a new Venue record in the db, instead
  # modify data to be the data object returned from db insertion

  form = ArtistForm(request.form)
  print("Forma ", form )
  print("Forma R ", request.form )
   
  #if request.method == 'POST' and form.validate_on_submit(): # igual q liena siguiente
  if form.validate_on_submit(): 
    
    artist = Artist(
      name=request.form["name"],
      city=request.form["city"],
      state=request.form["state"],
      phone=request.form["phone"],
      facebook_link=request.form["facebook_link"]
    )

    if "image_link" in request.form:
      artist.image_link = request.form["image_link"]
    if "website" in request.form:
      artist.website = request.form["website"]

    formGenres = request.form.getlist("genres")
    for genre in formGenres:
      artistGenre = ArtistGenres()
      artistGenre.genre = genre
      # Assign genre to artist
      artistGenre.Artist = artist
    
    #artist = Artist()
    #form.populate_obj(artist)
    
    print("Artist ", artist)
    print("Forma ", form )
    print("Generos (tam)", len(request.form.getlist("genres")) )
    print("Request ", request.form) 

    
    try:
      db.session.add(artist)
      db.session.commit()

      flash('Artist ' + artist.name + ' was successfully listed!')
      print('Artista creado')
    except: 
      db.session.rollback()
      flash('An error occurred. Artist ' + artist.name + ' could not be listed.')
      print('Error: Artista no creado')
      print(sys.exc_info())
    finally: 
      db.session.close()
    
  else:
    flash('An error occurred. Artist ' + request.form["name"] + ' failed (validation error).')
    print('Errror: forma no válida', form.errors) 

  # on successful db insert, flash success
  # flash('Artist ' + request.form['name'] + ' was successfully listed!')
  # on unsuccessful db insert, flash an error instead.
  # e.g., flash('An error occurred. Artist ' + data.name + ' could not be listed.')
  return render_template('pages/home.html')


@app.route('/artists/<artist_id>', methods=['DELETE'])
def delete_artist(artist_id):

  try:
    print('************************')
    print("Borrar Aritsta", artist_id)
  
    Show.query.filter_by(artist_id=artist_id).delete()
    ArtistGenres.query.filter_by(artist_id=artist_id).delete()
    Artist.query.filter_by(id=artist_id).delete()

    db.session.commit()
    
  except:
    print('xxxxxxxxxxxxxxxx\nNo borré')

    db.session.rollback()
    print(sys.exc_info())

  finally:
    db.session.close()

  return  jsonify({'success': True})


#  Shows
#  ----------------------------------------------------------------

@app.route('/shows')
def shows():
  # displays list of shows at /shows
  # replace with real venues data.
  #       num_shows should be aggregated based on number of upcoming shows per venue.
  """
  data=[{
    "venue_id": 1,
    "venue_name": "The Musical Hop",
    "artist_id": 4,
    "artist_name": "Guns N Petals",
    "artist_image_link": "https://images.unsplash.com/photo-1549213783-8284d0336c4f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=300&q=80",
    "start_time": "2019-05-21T21:30:00.000Z"
  }, {
    "venue_id": 3,
    "venue_name": "Park Square Live Music & Coffee",
    "artist_id": 5,
    "artist_name": "Matt Quevedo",
    "artist_image_link": "https://images.unsplash.com/photo-1495223153807-b916f75de8c5?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80",
    "start_time": "2019-06-15T23:00:00.000Z"
  }, {
    "venue_id": 3,
    "venue_name": "Park Square Live Music & Coffee",
    "artist_id": 6,
    "artist_name": "The Wild Sax Band",
    "artist_image_link": "https://images.unsplash.com/photo-1558369981-f9ca78462e61?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=794&q=80",
    "start_time": "2035-04-01T20:00:00.000Z"
  }, {
    "venue_id": 3,
    "venue_name": "Park Square Live Music & Coffee",
    "artist_id": 6,
    "artist_name": "The Wild Sax Band",
    "artist_image_link": "https://images.unsplash.com/photo-1558369981-f9ca78462e61?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=794&q=80",
    "start_time": "2035-04-08T20:00:00.000Z"
  }, {
    "venue_id": 3,
    "venue_name": "Park Square Live Music & Coffee",
    "artist_id": 6,
    "artist_name": "The Wild Sax Band",
    "artist_image_link": "https://images.unsplash.com/photo-1558369981-f9ca78462e61?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=794&q=80",
    "start_time": "2035-04-15T20:00:00.000Z"
  }]
  """

  data = []
  shows_list = Show.query.all()

  for show in shows_list:
    content = {}
    content["venue_id"] = show.venue.id
    content["venue_name"] = show.venue.name
    content["artist_id"] = show.artist.id
    content["artist_name"] = show.artist.name
    content["artist_image_link"] = show.artist.image_link
    content["start_time"] = show.start_time.isoformat() #strftime("%m/%d/%Y, %H:%M:%S")
    print(content["start_time"])

    data.append(content)

  return render_template('pages/shows.html', shows=data)


@app.route('/shows/create')
def create_shows():
  # renders form. do not touch.
  form = ShowForm()
  return render_template('forms/new_show.html', form=form)


@app.route('/shows/create', methods=['POST'])
def create_show_submission():
  # called to create new shows in the db, upon submitting new show listing form
  # insert form data as a new Show record in the db, instead

  form = ShowForm(request.form)

  if request.method == 'POST' and form.validate():
    venue_id = request.form['venue_id']
    artist_id = request.form['artist_id']
    start_time = request.form['start_time']

    selected_venue = Venue.query.get(venue_id)
    selected_artist = Artist.query.get(artist_id)

    show = Show(start_time=start_time)
    show.artist = selected_artist
    show.venue = selected_venue
    selected_venue.artists.append(show)
    selected_artist.venues.append(show)

    
    try:
      db.session.add(selected_venue)
      db.session.commit()

      flash('Show ' + start_time + ' was successfully listed!')
      print('Show creado')
    except: 
      db.session.rollback()
      flash('An error occurred. Show ' + start_time + ' could not be listed.')
      print('Error: Show no creado')
      print(sys.exc_info())
    finally: 
      db.session.close()
    

  # on successful db insert, flash success
  #flash('Show was successfully listed!')
  # on unsuccessful db insert, flash an error instead.
  # e.g., flash('An error occurred. Show could not be listed.')
  # see: http://flask.pocoo.org/docs/1.0/patterns/flashing/
  return render_template('pages/home.html')


@app.errorhandler(404)
def not_found_error(error):
    return render_template('errors/404.html'), 404

@app.errorhandler(500)
def server_error(error):
    return render_template('errors/500.html'), 500


#----------------------------------------------------------------------------#
# Auxiliars.
#----------------------------------------------------------------------------#

def getShowVenues(query_shows):
  shows = []
  for ps in query_shows:
    content = {}
    venue = Venue.query.get(ps.venue_id)

    content["venue_id"] = venue.id
    content["venue_name"] = venue.name
    content["venue_image_link"] = venue.image_link
    content["start_time"] = ps.start_time.isoformat()
    shows.append(content)

  return shows

def getShowArtists(query_shows):
  shows = []
  for ps in query_shows:
    content = {}
    aritist = Artist.query.get(ps.artist_id)

    content["artist_id"] = aritist.id
    content["artist_name"] = aritist.name
    content["artist_image_link"] = aritist.image_link
    content["start_time"] = ps.start_time.isoformat()
    shows.append(content)

  return shows



if not app.debug:
    file_handler = FileHandler('error.log')
    file_handler.setFormatter(
        Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')
    )
    app.logger.setLevel(logging.INFO)
    file_handler.setLevel(logging.INFO)
    app.logger.addHandler(file_handler)
    app.logger.info('errors')

#----------------------------------------------------------------------------#
# Launch.
#----------------------------------------------------------------------------#

# Default port:
if __name__ == '__main__':
    app.run()

# Or specify port manually:
'''
if __name__ == '__main__':
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)
'''
