import sqlite3
from dates.date_converter import process_date

IOS_ATTACHMENT_PATH = "/var/mobile/Library/SMS/Attachments"
IOS_ATTACHMENT_PATH_REL = "~/Library/SMS/Attachments"
def replace_ios_path(path, attachment_dir):
    if path.find(IOS_ATTACHMENT_PATH) != -1:
        return path.replace(IOS_ATTACHMENT_PATH, attachment_dir)
    elif path.find(IOS_ATTACHMENT_PATH_REL) != -1:
        return path.replace(IOS_ATTACHMENT_PATH_REL, attachment_dir)
    else:
        raise ValueError("Cannot handle path: %s" % path)

def get_attachments_sql_command():
    return """
    SELECT attachment.filename, attachment.created_date, attachment.transfer_name
    FROM attachment
    WHERE attachment.ROWID IN
        (SELECT attachment_id
         FROM
            (SELECT message_id
             FROM chat JOIN chat_message_join ON
                  chat.ROWID = chat_message_join.chat_id
             WHERE chat.chat_identifier = ?) AS message_ids
            NATURAL JOIN message_attachment_join)
    ORDER BY attachment.created_date ASC"""

def get_attachments(db_path, phone_number, attachment_dir):
    # Open database
    db = sqlite3.connect(db_path)
    cursor = db.cursor()
    # Tuple with phone number argument
    arg_tup = (phone_number,)
    # Get messages for phone number
    cursor.execute(get_attachments_sql_command(), arg_tup)
    # Process results
    for attachment in cursor:
        filepath = attachment[0]
        # Replace iOS path with given attachments folder path
        filepath = replace_ios_path(filepath, attachment_dir)
        received_date = process_date(attachment[1], "%Y-%m_%d-%H_%M_%S")
        name = attachment[2]
        yield filepath, received_date, name