#!/usr/bin/python2
# Copyright (c) 2015 Gris Ge
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
#     The above copyright notice and this permission notice shall be included
#     in all copies or substantial portions of the Software.
#
#     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
#     OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
#     MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
#     IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
#     CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
#     TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
#     SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
#
# Author: Gris Ge <cnfourt@gmail.com>

# Code was edit based on
# https://github.com/mpetroff/kindle-weather-display.git
# Which is also MIT license.
#
# Kindle Weather Display
# Matthew Petroff (http://mpetroff.net/)
# September 2012

import codecs
import datetime
import os
import sys

from weather_api import WeatherAPI
from argparse import ArgumentParser
from aqi import aqi_get
from sci import sci_get

CODE_FOLDER = os.path.dirname(os.path.realpath(__file__))
OUTPUT = "/var/www/html/weather/weather.png"
TMP_OUTPUT = "%s/weather.png" % CODE_FOLDER
SVG_PORTRAIT_FILE = "%s/weather-script-preprocess.svg" % CODE_FOLDER
SVG_LANSCAPE_FILE = "%s/weather-script-preprocess-landscape.svg" % CODE_FOLDER
SVG_FILE = SVG_PORTRAIT_FILE
SVG_OUTPUT = "%s/weather-script-output.svg" % CODE_FOLDER
MAX_WEATHER_DAY_COUNT = 3
AQI_CITY = None


def _exec(cmd):
    rc = os.system(cmd)
    if (rc != 0):
        print("`%s` failed with error %d" % (cmd, rc))
        exit(rc)

if len(sys.argv) < 4:
    print("Need 3 or more argument for API key, latitude, longitud, "
          "[is_landscape] [aqi_city_name_for_landscape]")
    exit(1)

weather_obj = WeatherAPI(sys.argv[1], sys.argv[2], sys.argv[3])

if len(sys.argv) >= 5 and sys.argv[4] != 0:
    SVG_FILE = SVG_LANSCAPE_FILE

if len(sys.argv) >= 6 and sys.argv[5]:
    AQI_CITY = sys.argv[5]

# Open SVG to process
output = codecs.open(SVG_FILE, "r", encoding="utf-8").read()

_MAP = {
    "$I": WeatherAPI.condition,
    "$H": WeatherAPI.temp_max,
    "$L": WeatherAPI.temp_min,
}

for x in _MAP.keys():
    for i in range(MAX_WEATHER_DAY_COUNT + 1):
        output = output.replace("%s%d" % (x, i),
                                "%s" % _MAP[x](weather_obj, i))

# Replace refresh time
output = output.replace("$TIME",
                        datetime.datetime.now().strftime("%b %d %a %H:%M"))

# Updaet AQI. TODO(Gris Ge): still place holder yet.
if AQI_CITY is not None:
    output = output.replace("$AQI", str(aqi_get(AQI_CITY)))

(sci, sci_change) = sci_get()
output = output.replace("$SCI", str(sci))
output = output.replace("$SCHG", str(sci_change))

day_one = weather_obj.today

# Insert days of week
one_day = datetime.timedelta(days=1)
days_of_week = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]

for i in range(MAX_WEATHER_DAY_COUNT + 1):
    output = output.replace("$D%s" % i,
                            days_of_week[(day_one + i * one_day).weekday()])

# Write output
codecs.open(SVG_OUTPUT, "w", encoding="utf-8").write(output)

_exec("rsvg-convert --background-color=white -o %s %s" %
      (TMP_OUTPUT, SVG_OUTPUT))
_exec("pngcrush -c 0 -ow %s 1>/dev/null 2>&1" % TMP_OUTPUT)
_exec("mv -f '%s' '%s'" % (TMP_OUTPUT, OUTPUT))

@@ -1970,16 +1970,36 @@
  = None%0A
+INCLUDE_SCI = False%0A
 %0A%0Adef _e
@@ -2270,16 +2270,30 @@
 ndscape%5D
+ %5Binclude_sci%5D
 %22)%0A    e
@@ -2406,17 +2406,19 @@
 v%5B4%5D != 
-0
+'0'
 :%0A    SV
@@ -2512,16 +2512,86 @@
 rgv%5B5%5D%0A%0A
+if len(sys.argv) %3E= 7 and sys.argv%5B6%5D != '0':%0A    INCLUDE_SCI = True%0A%0A
 # Open S
@@ -3227,16 +3227,36 @@
 ITY)))%0A%0A
+if INCLUDE_SCI:%0A    
 (sci, sc
@@ -3277,16 +3277,20 @@
 i_get()%0A
+    
 output =
@@ -3323,16 +3323,20 @@
 r(sci))%0A
+    
 output =
@@ -3376,16 +3376,73 @@
 change))
+%0Aelse:%0A    output = output.replace(%22SCI: $SCI $SCHG%22, %22%22)
 %0A%0Aday_on

Allow user to disable SCI display