#!/usr/bin/python

# 2600.py
# 
# 10/19/2015
# w.r.e.c.

# install python-BeautifulSoup
from BeautifulSoup import BeautifulSoup
# install python-mysqldb
import MySQLdb
from urllib2 import urlopen
import cStringIO
from PIL import Image
import socket
import subprocess

import sys
import pprint


# parameters
if len (sys.argv) < 3:
  print "parameters required: Period Year {optional Update}"
  print "  (Period=Spring/Summer/Autumn/Winter)"
  sys.exit (0)

Period = sys.argv [1]
print "Period=", Period
if Period == "Spring":
  Quarter = "1"
elif Period == "Summer":
  Quarter = "2"
elif Period == "Autumn":
  Quarter = "3"
elif Period == "Winter":
  Quarter = "4"
else:
  print "invalid period: " + Period
  sys.exit (0)
print "Quarter=", Quarter

Year = sys.argv [2]
print "Year=", Year
Volume = str (int (Year) - 1983)
print "Volume=", Volume

Update = False
if len (sys.argv) == 4:
  if sys.argv [3] == "Update":
    Update = True
print "Update=", Update


# build parameters
Filename = Period + Year + ".gif"

#url = "http://store.2600.com/collections/2010-2015/products/autumn-2015"
if int (Year) >= 2010 and int (Year) <= 2015:
  Range = "2010-2015"
elif int (Year) >= 2015 and int (Year) <= 2020:
  Range = "2016-2020"
else:
  print "invalid year: " + Year
  sys.exit (0)
  
url = "http://store.2600.com/collections/" + Range + "/products/" + Period.lower () + "-" + Year
#if (int (Year) == 2015 and Period == "Winter"):
#  url = "https://store.2600.com/collections/back-issues/products/winter-2015-2016"
if (Period == "Winter"):
 url += "-" + str (int (Year)+1)

print url


# get 2600 store web page
socket.setdefaulttimeout (30)
try:
  html = urlopen (url).read()
except Exception, e:
  print "urlopen: ", e
  sys.exit (0)

soup =  BeautifulSoup (html)
td = soup.find (id="productPhotoImg")

#print td
#pprint.pprint (td)

text = str (td)
print text

i = text.find ("src=")
#j = text.find ("alt=")
#url = "http:" + text[i+5:j-2]
j = text.find ("?v=")
url = "http:" + text[i+5:j]
print url


#https://stackoverflow.com/questions/7391945/how-do-i-read-image-data-from-a-url-in-python
#https://stackoverflow.com/questions/4025545/problem-writing-image-file-in-python-with-pil
#url = "http://cdn.shopify.com/s/files/1/0837/3445/products/32-3_Cover_large.jpg"
file = cStringIO.StringIO (urlopen (url).read())
img = Image.open (file)
img.save (Period + Year + ".jpg")

cmd = "convert -resize 112x180 " + Period + Year + ".jpg " + Period + Year + ".gif"
print cmd
p = subprocess.Popen (cmd, shell=True)
retval = p.wait ()
print "retval=" + str (retval)

#/* open db */
conn = MySQLdb.connect (host = "localhost", user = "App2600", passwd = "A2p6p0", db = "2600")
#conn = MySQLdb.connect (host = "localhost", user = "root", passwd = "1.root_2", db = "2600")
cursor = conn.cursor ()


# does issue exist?
sql = "SELECT * FROM Issues WHERE Period = '" + Period + "' AND IssueYear = " + Year + ";"
print sql
cursor.execute (sql)

if cursor.rowcount > 0:
  row = cursor.fetchone ()
  IssuesID = str (row[0])
  print IssuesID
else:
  sql  = "INSERT INTO Issues (Period, IssueYear, CoverLink, BackCoverLink, Quarter, Volume, Pages) "
  sql += "VALUES ('" + Period + "'," + Year + ",'FrontCoverImages/" + Filename + "',"
  sql +=          "'BackCoverImages/" + Filename + "'," + Quarter + "," + Volume + ",68);"
  print sql
  cursor.execute (sql)
  IssuesID = str (cursor.lastrowid)
  print "IssuesID=", IssuesID
  if IssuesID == 0:
    conn.rollback ()
    sys.exit (1)
  else:
    if Update:
      conn.commit ()
      print "commit"


#td = soup.find (class="product-description rte")
#pprint.pprint (td)
print
tds = soup.findAll ("li")

for td in tds:
  text = str (td)
  i = text.find ("span")
  if i < 1:
    i = text.find ("href")
    if i < 1:
      i = text.find ("&copy")
      if i < 1:
        #print text
        tmp = text.replace ("<li>","")
        Title = tmp.replace ("</li>","")
        print Title
        #print "===="
        sql  = "INSERT INTO Articles (IssuesID, AuthorsID, Title, Synopsis) "
        ##sql += "VALUES (" + IssuesID + ",1,'" + Title + "','');"
        sql += "VALUES (" + IssuesID + ",1,%s,'');"
        print sql
        ##cursor.execute (sql)
        try:
          cursor.execute (sql, [Title])
        except conn.Error as error:
          if error.args[0] == 1062:
            print ("Error: {}", format (error))

if Update:
  conn.commit ()
  print "commit"


# /* done */
cursor.close ()
conn.close ()