#!/usr/bin/env python

#################################################################################################
#                                Configuration/Settings Section                                 #
#################################################################################################
#
BASE_FOLDER='media_fr_phonesKK'
#Directory to store videos. Change according to your needs                                      #
VIDEO_FOLDER="videos"                                 
#                                                                                               #
#Directory to store photos. Change according to your needs                                      #
IMAGE_FOLDER="photos"                                                 
#                                                                                               #
#Change the bluetooth address and folder name here according to your situation and needs.
#The format is 'bluetooth address':'folder name'
#For example, F8:E0:79:31:7F:C1 is John's Phone and D2:E0:79:31:7F:Z3 is Sue's phone:           #
#so enter 'F8:E0:79:31:7F:C1':'John',                                                           #
#         'D2:E0:79:31:7F:Z3':'Sue'
#The above entry will create a final folder called 'John' that will contain his media files     #
#and a final folder called 'Sue' that will contain her media files                              #
#The value of VIDEO_FOLDER and IMAGE_FOLDER will be parent folder of these final folder             #
#The bluetooth address and folder name MUST be in quotes                                        #
bt_db = {
            'F8:E0:79:31:7F:C1':'bill',
            'F8:E0:79:31:7F:C0':'george',
            '78:1F:DB:E2:FE:ED':'barry'
        }
#                                                                                               #
#################################################################################################

import sys
import string
import subprocess
import re
import os

FROM = None
FILE_NAME = None
SUB_FOLDER = None
LENGTH = None
MIMETYPE = None
HOME_FOLDER = os.path.expanduser('~')

'''
Get the value of media type.
Params: Mime type (eg. 'image/jpeg' or 'video/mp4')
Returns: Media type (eg.'image' or 'video')
'''
def media_type(mime_type):
    values = string.split(mime_type, '/', 1)
    return values[0]

'''
Get the bluetooth address
Params: String (eg. 'bluetooth/[F8:E0:79:31:7F:C0]:9')
Return: Bluetooth address (eg. 'F8:E0:79:31:7F:C0')
'''
def bluetooth_addr(from_addr):
    pattern = '\[(.*?)\]'
    re_proc = re.compile(pattern)
    bt_addr = re_proc.findall(from_addr)
    return bt_addr[0]

'''
Read in binary data from standard input and write it to file in the filesystem
Params: Full pathname of the file  (eg. '/home/foo/bar.jpg')
'''
def copy_to_folder(path):
    block_sz = 8192    
    file = open(path, 'wb')
    while True:
        buffer = sys.stdin.read(block_sz)
        if not buffer:
            break
        file.write(buffer)
    file.close()

'''
Param1: File name (eg. 'IMG_2333.jpg')
Param2: Mime type (eg. 'image/jpeg')
Param3: String containing bluetooth address (eg. 'bluetooth/[F8:E0:79:31:7F:C0]:9')
Returns: Full pathname of the file (eg. /home/pi/foo/bar.jpg')
'''
def dest_filepath(FILE_NAME, MIMETYPE, FROM):
    SUB_FOLDER = os.path.join(HOME_FOLDER, BASE_FOLDER)
    if(media_type(MIMETYPE).lower() == 'video'):
        SUB_FOLDER = os.path.join(SUB_FOLDER, VIDEO_FOLDER)
    elif(media_type(MIMETYPE).lower() == 'image'):
        SUB_FOLDER = os.path.join(SUB_FOLDER,IMAGE_FOLDER)

    for bt_addr in bt_db:
        if(bluetooth_addr(FROM).strip() == bt_addr):
            folder = bt_db.get(bt_addr)
            SUB_FOLDER = os.path.join(SUB_FOLDER, folder)
            break

    if os.path.exists(SUB_FOLDER) is False:
        os.makedirs(SUB_FOLDER)

    FILE_PATH = os.path.join(SUB_FOLDER, FILE_NAME)
    print >> sys.stderr, 'File path is ' + FILE_PATH
    return FILE_PATH

##The following codes will read data from obexpushd daemon program,
##sort the data according to media type and bluetooth device.
##Finally, it saves the data in separate folders in which each bluetooth device
##will have its own folder
while True:
    line = sys.stdin.readline()
    print >> sys.stderr, line
    param_value = string.split(line, ':', 1)

    if(param_value[0] == '\n'):
        break

    TAG = string.strip(param_value[0])    
    VALUE = string.strip(param_value[1])
    print >> sys.stderr, param_value
    print >> sys.stderr, "value = " + VALUE
    if(TAG == 'From'):
        FROM = VALUE
    if(TAG == 'Name'):
        FILE_NAME = VALUE
    if(TAG == 'Path'):
        SUB_PATH = VALUE
    if(TAG == 'Length'):
        LENGTH = VALUE
    if(TAG == 'Type'):
        MIMETYPE = VALUE

filepath = dest_filepath(FILE_NAME, MIMETYPE, FROM)

##Tell Bluetooth sending device to continue pushing
subprocess.call(['echo', 'OK'])

copy_to_folder(filepath)

