# coding=UTF-8
import urllib
import datetime
from dateutil.parser import parse
import time
from textwrap import wrap
import re

city = state = place = ""
lat = lon = []

from etm.rc import *
meta_regex = re.compile(r'^(<meta|.*<br)')
s_regex = re.compile(' ', re.M|re.L|re.U)
n_regex = re.compile('[\r\n]', re.M|re.L|re.U)

from HTMLParser import HTMLParser

class MyHTMLParser(HTMLParser):
    
    def __init__(self):
        HTMLParser.__init__(self)
        self.capture = False
        self.pre = False
        self.more = True
        self.output = []
        self.para = ''
        self.skip = False

    def handle_starttag(self, tag, attrs):
        if tag in ['p', 'pre']:
            if tag == 'pre':
                self.pre = True
            self.capture = True
        elif tag == "strong":
            self.output.append('')
        elif tag == 'hr':
            self.more = False

    def handle_endtag(self, tag):
        if tag in ['p', 'pre']:
            if tag == 'pre':
                self.pre = False
                self.output.append('')
            else:
                
                l = wrap(self.para, width=70)
                self.output.extend(l)
                self.output.append('')
                self.para = ''
            self.capture = False

    def handle_data(self, text):
        if self.more and self.capture:
            if self.pre:
                text = text.rstrip()
                if text:
                    self.skip = False
                    out = []
                    parts = text.split('\n')
                    for part in parts:
                        p = part.rstrip()
                        if p:
                            self.output.append("%s\n" % p)
                else:
                    self.skip = True
            else:
                l = text.split()
                self.para += " ".join(l)
            
    def output(self):
        return self.output

def getsunmoon(d=None):
    data = {}
    if len(location) == 2:
        ffx = 1
        data['place'] = location[0]
        data['st'] = location[1]
    elif len(location) == 7:
        ffx = 2
        data['place'] = location[0]
        if location[1].upper() == 'E':
            data['xx0'] = 1
        elif location[1].upper() == 'W':
            data['xx0'] = -1
        data['xx1'] = location[2]
        data['xx2'] = location[3]
        
        if location[4].upper() == 'N':
            data['yy0'] = 1
        elif location[4].upper() == 'S':
            data['yy0'] = -1
        data['yy1'] = location[5]
        data['yy2'] = location[6]
        
        if time.localtime().tm_isdst:
            utcoffset = time.altzone/3600
        else:
            utcoffset = time.timezone/3600
        if utcoffset < 0:
            # east of Greenwich
            data['zz0'] = 1
            data['zz1'] = -utcoffset
        else:
            # west of Greenwich
            data['zz0'] = -1
            data['zz1'] = utcoffset
    else:
        return ['There is a problem with the setting for \'location\' in ~/.etmrc.']
    
    if d:
        year, month, day = parse(d).strftime("%Y %m %d").split()
    else:
        year, month, day = datetime.datetime.now().strftime("%Y %m %d").split()
    
    # this hack is needed to put FFX and xxy first - otherwise usno uses latitude degrees as the year.
    url_data = "FFX=%s&xxy=%s&xxm=%s&xxd=%s&" % (ffx, year, month, day)
    url_data += urllib.urlencode(data)
    url = 'http://aa.usno.navy.mil/cgi-bin/aa_pap.pl'
    try:
        data = urllib.urlopen(url, url_data).read()
        data = s_regex.sub('.', data)
        myparser = MyHTMLParser()
        myparser.feed(data.encode('UTF-8'))
        myparser.close()
        return(myparser.output)
    except:
        return ['Network problem - could not obtain USNO sun and moon data.']    


if __name__ == "__main__":
    import sys
    location = ['Chapel Hill', 'NC']
    
    # location = ['Home', 'W',79,0, 'N',35,54]
    l = [None]
    if len(sys.argv) > 1:
        l.append(" ".join(sys.argv[1:]))
    for d in l:
        out = getsunmoon(d)
        print "for date: %s" % d
        print "".join(out)