import urlparse
import os, sys, re
from flask import Flask, request, jsonify, abort, json, make_response
from msc_apps import *
import psycopg2, psycopg2.extras
 
sqlconn = sql_connect()

app = Flask(__name__)
app.debug = True

@app.route('/<prop_id>')
def getproperty(prop_id):
    try:
        property_ = int(re.sub(r'\D+', '', prop_id.split('.')[0] ) ) #check alphanumeric
    except ValueError:
        abort(make_response('This endpoint only consumes valid input', 400))

    sqlconn.execute("select * from transactions t, smartproperties sp where sp.createtxdbserialnum = t.txdbserialnum and sp.propertyid=" + str(property_) )
    ROWS= sqlconn.fetchall()

    #print property_, ROWS[0]

    def dehexify(hex_str):
        temp_str=[]
        for let in hex_str:
            if ord(let) < 128:
                temp_str.append(let)
            else:
                temp_str.append('?')
        return ''.join(temp_str)
                   
    txData = ROWS[0][:-1]
    mpData = ROWS[0][-1]
    
    #TODO FIXME Need to dehexify property* fields
    txType = txData[3]

    #map tx 50,51, and 54 data into this data blob
    ret = { 
      "block": txData[9], 
      "currencyId": mpData['propertyid'], 
      "currency_str": "Smart Property", 
      "ecosystem": '1' if txData[5] == 'Production' else '2', 
      "from_address": txData[13], 
      "previous_property_id": "(null)", #TODO FIXME
      "propertyCategory": mpData['category'], 
      "propertyData": mpData['data'], 
      "propertyName": mpData['name'], 
      "propertySubcategory": mpData['subcategory'], 
      "propertyUrl": mpData['url'], 
      "propertyType": '0002' if mpData['divisible'] == True else '0001', 
      "formatted_property_type": int('0002' if mpData['divisible'] == True else '0001'), 
      "transactionType": txData[3], 
      "transactionVersion": txData[4], 
      "tx_hash": txData[0], 
      "tx_time": '(null)' #TODO FIXME
    }

    if txType == 50: ret['numberOfProperties'] = mpData['totaltokens']; 
    
    if txType == 51:
      ret['numberOfProperties'] = mpData['tokensperunit']; 
      ret['currencyIdentifierDesired'] = mpData['propertyiddesired']
      ret['deadline'] = mpData['deadline']
      ret['earlybirdBonus'] = mpData['earlybonus']
      ret['percentageForIssuer'] = mpData['percenttoissuer']
      
    if txType == 54:
      ret['numberOfProperties'] = mpData['totaltokens']; 
      ret['issuances'] = mpData['issuances']

    #Fields that didn't make it, may become relevant at a later time

    #"tx_type_str": "Fundraiser property creation"
    #"formatted_amount": 0, 
    #"formatted_ecosystem": 1, 
    #"formatted_previous_property_id": 0, 
    #"formatted_transactionType": 51, 
    #"formatted_transactionVersion": 0, 
    #"baseCoin": "00", 
    #"color": "bgc-new", 
    #"dataSequenceNum": "01", 
    #"details": "unknown", 
    #"icon": "unknown", 
    #"index": "215", 
    #"invalid": false, 
    #"method": "multisig", 
    #"to_address": "1ARjWDkZ7kT9fwjPrjcQyvbXDkEySzKHwu", 
    #"tx_method_str": "multisig", 
    #"update_fs": false


    return json.dumps([ ret ]) #only send back mapped schema 

@@ -505,16 +505,28 @@
 t * from
+ txjson txj,
  transac
@@ -583,16 +583,63 @@
 ialnum =
+ txj.txdbserialnum and sp.createtxdbserialnum =
  t.txdbs
@@ -991,24 +991,77 @@
             
+%0A    txJson = ROWS%5B0%5D%5B:3%5D%0A    ROWS = %5B ROWS%5B0%5D%5B3:%5D %5D%0A
   %0A    txDat
@@ -1106,62 +1106,8 @@
 -1%5D%0A
-    %0A    #TODO FIXME Need to dehexify property* fields
 %0A   
@@ -1469,32 +1469,42 @@
 opertyCategory%22:
+ dehexify(
  mpData%5B'categor
@@ -1498,32 +1498,34 @@
 Data%5B'category'%5D
+ )
 , %0A      %22proper
@@ -1532,16 +1532,26 @@
 tyData%22:
+ dehexify(
  mpData%5B
@@ -1557,16 +1557,18 @@
 %5B'data'%5D
+ )
 , %0A     
@@ -1583,16 +1583,26 @@
 tyName%22:
+ dehexify(
  mpData%5B
@@ -1608,16 +1608,18 @@
 %5B'name'%5D
+ )
 , %0A     
@@ -1641,16 +1641,26 @@
 tegory%22:
+ dehexify(
  mpData%5B
@@ -1673,16 +1673,18 @@
 tegory'%5D
+ )
 , %0A     
@@ -1698,16 +1698,26 @@
 rtyUrl%22:
+ dehexify(
  mpData%5B
@@ -1722,16 +1722,18 @@
 a%5B'url'%5D
+ )
 , %0A     
@@ -2018,28 +2018,31 @@
 e%22: 
-'(null)' #TODO FIXME
+txJson%5B-1%5D%5B'blocktime'%5D
 %0A   

Add blocktime and proper dehexification for property strings