#!/usr/bin/env python3

# [Gedit Tool]
# Name=Send to fpaste
# Name[as]=fpaste লৈ পঠাওক
# Name[bs]=Pošalji u fpaste
# Name[eu]=Bidali fpaste-ra
# Name[fi]=Lähetä fpasteen
# Name[it]=Inva a fpaste
# Name[nl]=Naar fpaste sturen
# Comment=Paste selected text or current document to fpaste
# Comment[da]=Indsæt markerede tekst eller aktuelt dokument i fpaste
# Comment[eu]=Hautatutako testua edo uneko dokumentua 'fpaste' gunera bidaltzen du
# Comment[fa]=متن انتخاب شده یا سند فعلی را به fpaste میچسباند
# Comment[th]=แปะข้อความที่เลือกหรือเอกสารปัจจุบันไปยัง fpaste
# Comment[vi]=Dán đoạn văn bản đa chọn hay tài liệu hiện tại vào fpaste
# Comment[zh_TW]=將選取的文字或目前的文件貼到 fpaste
# Input=selection-document
# Output=output-panel
# Shortcut=<Shift><Super>p
# Applicability=always
# Save-files=nothing
# Languages=
# 
# 

import os, urllib, json, sys, urllib.request
from gi.repository import Gtk, Gdk

lang = os.getenv('GEDIT_CURRRENT_DOCUMENT_LANGUAGE')
if lang is None:
    lang = "text"

current_document_path = os.getenv('GEDIT_CURRENT_DOCUMENT_PATH')
selected_text = os.getenv('GEDIT_SELECTED_TEXT')

if selected_text is None:
    selected_text = sys.stdin.read()

url_params = urllib.parse.urlencode({'paste_data': selected_text, 'paste_lang': lang, 'mode':'json', 'api_submit':'true'})
openfpaste = urllib.request.urlopen("http://fpaste.org", bytes(url_params, 'utf-8')).read().decode("utf-8")
final_data = json.loads(openfpaste)

paste_url = "http://fpaste.org/" + final_data['result']['id']

print(paste_url + " has been copied to clipboard.")

disp = Gdk.Display.get_default()
clipper = Gtk.Clipboard.get_for_display(disp, Gdk.SELECTION_CLIPBOARD)
clipper.set_text(paste_url, len(paste_url))
clipper.store()
