#!/usr/bin/python

import sys
import socket
import PBU2100
import time

#print sys.argv[1]


def hms12():
  t = time.localtime()

  if t[3] == 12:
    ts = '%02d:%02d:%02dPM' %((t[3]),t[4],t[5])
  elif t[3] == 0:
    ts = '%02d:%02d:%02dAM' %((t[3]+12),t[4],t[5])
  elif t[3] > 12:
    ts = '%02d:%02d:%02dPM' %((t[3]-12),t[4],t[5])
  else:
    ts = '%02d:%02d:%02dAM' %(t[3],t[4],t[5])
  return ts

sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', 44444))
sock.settimeout(5)

data = ''
try:
  s = sock.recv(1023)
  while len(s) > 0:
    data = data + s
    s = sock.recv(1023)
except socket.timeout:
  data = 'timeout!'


if data == 'timeout!':
  print data
else:
  if len(sys.argv) == 2:
    if sys.argv[1] == 'raw':
      print data
    if sys.argv[1] == 'text':
      d = PBU2100.convert(data)
      print  '%s, %s degF, %s deg at %4.1f MPH' % (hms12(),d['temp_out'],int(d['w_dir']),d['w_spd'])
    if sys.argv[1] == 'all':
      d = PBU2100.convert(data)
      print '%s \nIndoor temp = %sF \nOutdoor temp = %sF \n5 minute average wind: %s mph at %s degrees\ncurrent wind: %s mph at %s degrees\n'\
      % (hms12(),d['temp_in'],d['temp_out'],d['w_spd_peak5'],int(d['w_dir_peak5']),d['w_spd'],int(d['w_dir']))
      print 'Barometer =%s inHg \nRainfall = %s inches\nHumidity = %s\n'\
      % (d['barometer'],d['rain_today'],d['humidity_out'])
      print 'Indoor Humidity = %s\n'\
      % (d['humidity_in'])
  else:
    print 'wx_client [raw|text|all]'

sock.close()


