# import main Flask class and request object
from base64 import b64encode
import fcntl
# from http.client import sha1
from hashlib import sha1
import hmac
from http import client # import httplib
import json
import os
import pprint
import requests
import shutil
from subprocess import call, Popen
import sys
import tempfile
import time
import traceback

from urllib.parse import urlparse
import os
from flask import Flask, request
from transifex.api import transifex_api
from transifex.native import init, tx
from transifex.native.parsing import SourceString
# create the Flask app
app = Flask(__name__)

@app.route('/query-example')
def transifex_demo():
    token = os.getenv('token')
    secret = os.getenv('secret')
    print("token value",token)
    init(token=token, languages=['el', 'fr', 'en'], secret=secret)
    # Add some strings to push
    strings = [SourceString('My Addresses')]
    response_content = tx.push_source_strings(strings)
    tx.fetch_translations()
    el_translation = tx.translate('My Addresses', 'fr')
    return print(el_translation)

# @app.route('/commit-example')
# def commitTranslatedLanguage(ts, lang):
#     call(["lrelease-qt4", "src/translations/bitmessage.pro"])
#     call(["git", "add", "src/translations/bitmessage_" + lang + ".ts", "src/translations/bitmessage_" + lang + ".qm"])
#     call(["git", "commit", "-q", "-S", "-m", "Auto-updated language %s from transifex" % (lang)])
#     newbranch = "translate_" + lang + "_" + str(ts)
#     call(["git", "push", "-q", "translations", newbranch + ":" + newbranch])
#     request = {
#         "title": "Translation update " + lang,
#         "body": "Auto-updated from transifex",
#         "head": "PyBitmessageTranslations:" + newbranch,
#         "base": branch
#     }
#     headers = {"Authorization": "token " + gitHubToken}
#     response = requests.post("https://api.github.com/repos/Bitmessage/PyBitmessage/pulls",
#         headers=headers, data=json.dumps(request))
#     # TODO: save pull request number
#     return response
# #    print "JSON dumps request: %s" % (json.dumps(request))
# #    print "Response from github for pull request: %i, %s" % (response.status_code, response.content)



# def updateLocalTranslationSource():
#     call(["git", "stash", "-q"])
#     call(["git", "checkout", "-q", branch])
#     call(["git", "pull", "-q"])
#     call(["pylupdate4", "src/translations/bitmessage.pro"])

# def uploadTranslationSource():
#     headers = {"Authorization": "Basic " + b64encode(transifexUsername + ":" + transifexPassword)}
#     response = requests.put("https://www.transifex.com/api/2/project/pybitmessage/resource/pybitmessage/content/",
#         headers=headers, files={'bitmessage_en.ts': open("src/translations/bitmessage_en.ts", "rb")})
#     return response

@app.route('/upload-source')
def upload_source():
    async_job(id)
    return 'ok'

def async_job(id):
    response = requests.get("http://www.transifex.com/bitmessage-project/pybitmessage/upload_source/$BUILDBOT_JOBID" + id +"/")
    api_token = ''
    transifex_api.setup(auth=api_token)
    # transifex_api.Organization.list()
    organization = transifex_api.Organization.get(slug="bitmessage-project")
    project = organization.fetch('projects').get(slug="pybitmessage-test")
    language = transifex_api.Language.get(code="fr")
    resource = project.fetch('resources').get(slug="messagespot")
    content = "The new source file content"
    with open(resource,'rb') as f:
        upload = transifex_api.ResourceStringsAsyncUpload.create_with_form(
        data={'resource': resource.id},
        files={'content': f},
        )
        return "done"
    # transifex_api.ResourceStringsAsyncUpload.upload(resource, content)
    while not response:
        sleep_time = time.sleep(1) 
        sleep_time+=1
        if sleep_time == 600:
            return False
        





# def updateLocalTranslationDestination(ts, lang):
#     call(["git", "pull", "--all", "-q"])
#     call(["git", "stash", "-q"])
#     call(["git", "checkout", "-q", branch])
#     call(["git", "checkout", "-q", "-b", "translate_" + lang + "_" + str(ts)])
#     call(["git", "branch", "-q", "--set-upstream-to=origin/v0.6"])

# def downloadTranslatedLanguage(ts, lang):
#     headers = {"Authorization": "Basic " + b64encode(transifexUsername + ":" + transifexPassword)}
#     resname = "pybitmessage_" + lang + ".ts"
#     fname = "bitmessage_" + lang.lower() + ".ts"
#     with open("src/translations/" + fname, "wt") as handle:
#         response = requests.get("https://www.transifex.com/api/2/project/pybitmessage/resource/pybitmessage/translation/" + lang + "/",
#             headers=headers)
#         if response.ok:
#             content = json.loads(response.content)["content"]
#             handle.write(content.encode("utf-8"))
# #        print "Response from github for pull request: %i, %s" % (response.status_code, response.content)
#     return response

# def application():
#     if "Transifex" in environ.get("HTTP_USER_AGENT"):
# #        debug(environ)
# #        debug(body)
#         pass
#     if not verifyTransifexSignature(environ, body):
#         debug ("Verify Transifex Signature fail, but fuck them")
#     else:
#         debug ("Verify Transifex Signature ok")
# #            output, responseHeaders = returnMessage(False, "Checksum bad")
# #            start_response(status, responseHeaders)
# #            unlock()
# #            return [output]
#     try:
# #            debug(body)
#         payload = parse_qs(body)
# #            debug(payload)
#         if 'pybitmessage' in payload['project'] and 'pybitmessage' in payload['resource']:
#             if 'translated' in payload and '100' in payload['translated']:
#                 ts = int(time.time())
#                 updateLocalTranslationDestination(ts, payload['language'][0].lower())
#                 downloadTranslatedLanguage(ts, payload['language'][0])
#                 response = commitTranslatedLanguage(ts, payload['language'][0].lower())
#                 if response.ok:
#                     output, responseHeaders = returnMessage(True, "Processed.")
#                 else:
#                     output, responseHeaders = returnMessage(False, "Error: %i." % (response.status_code))
#             else:
#                 output, responseHeaders = returnMessage(False, "Nothing to do")
#         else:
#             output, responseHeaders = returnMessage(False, "Nothing to do")
#     except:
#         output, responseHeaders = returnMessage(True, "Not processing")
#     else:
#         debug("Unknown command %s" % (environ.get("HTTP_X_GITHUB_EVENT")))
#         output, responseHeaders = returnMessage(True, "Unknown command, ignoring")
# #    output = ''
# #    for k, v in environ.items():
# #        output += '%.40s %s\n' % (k, v)
#     #responseHeaders = sendFile("ffb8c8eb-3d3b-4306-b65e-e0d1fa4f7ea0")
#     start_response(status, responseHeaders)
#     unlock()
#     return [output]







if __name__ == '__main__':
    # run app in debug mode on port 5000
    app.run(debug=True, port=5000)