#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by i@BlahGeek.com at 2015-04-29

import os
import sys
import subprocess
import time
import Pashua

def send_output(line):
    sys.stdout.write(line.replace('\n', "[;n") + '\n')
    sys.stdout.flush()
    if sys.version_info[0] < 3:
        return raw_input()
    else:
        return input()

def read_clipboard():
    output = subprocess.check_output("pbpaste", shell=True)
    return output.decode('utf-8')

def pashua(config):
    return Pashua.run(config.encode('utf8'))
    
def notification_applescript(applescript):
    send_output("Notification_AppleScript: %s" % applescript)

def inputbox(title, prompt_text, field_name="Filename"):
    conf = "*.title = " + title + "\n" \
    + "txt.type = textfield" + "\n" \
    + "txt.label = " + prompt_text + "\n" \
    + "cb.type = cancelbutton"

    result = dz.pashua(conf)

    if result['cb'] == "1":
        fail("Cancelled")
    if not result['txt']:
        fail("%s cannot be empty" % field_name)
    return result['txt']

def save_value(value_name, value):
    send_output("Save_Value_Name: %s" % value_name)
    send_output("Save_Value: %s" % value)

def remove_value(value_name):
    send_output("Remove_Value_Name: %s" % value_name)

def add_dropbar(file_paths):
    if os.environ.get("sandboxed", False):
        tfolder = temp_folder()
        for path in file_paths:
            if not path.startswith(tfolder):
                error("Not Supported in Mac App Store version", "You cannot use the add_dropbar() API method in the Mac App Store version of Dropzone.\n\nPlease download the non-Mac App Store version of Dropzone.")
    for path in file_paths:
        send_output("Add_Dropbar: " + path)
    send_output("Complete_Add_Dropbar: 1")
    time.sleep(1)
    
def temp_folder():
    folder = os.environ["support_folder"] + "/Temp"
    if not os.path.exists(folder):
        os.mkdir(folder)
    return folder

def text(t):
    send_output("Text: %s" % (t if t else "0"))

def url(url, title=None):
    if title:
        send_output("URL_Title: %s" % title)
    send_output("URL: %s" % (url if url else "0"))

def percent(value):
    send_output("Progress: %s" % str(value))

def error(title, msg):
    send_output("Error_Title: %s" % title)
    send_output("Error: %s" % msg)
    sys.exit(0)

def alert(title, msg):
    send_output("Alert_Title: %s" % title)
    send_output("Alert: %s" % msg)

def fail(msg):
    send_output("Fail: %s" % msg)
    sys.exit(0)

def finish(msg):
    send_output("Finish_Message: %s" % msg)

def select_folder(prompt):
    return send_output("Select_Folder: %s" % prompt)

def begin(msg):
    send_output("Begin_Message: %s" % msg)

def determinate(value):
    send_output("Determinate: %s" % ("1" if value else "0"))
