class SmartlingApiExample:

    MY_API_KEY = "YOUR_API_KEY" #should be changed with read values
    MY_PROJECT_ID = "YOUR_PROJECT_ID" #should be changed with real values

    def __init__(self, useSandbox, uploadData, locale, new_name):
        self.getCredentials()

        useProxy = False
        if useProxy :
            proxySettings = ProxySettings("login", "password", "proxy_host", "proxy_port")
        else:
            proxySettings = None

        if useSandbox:
            self.fapi = SmartlingFileApiFactory().getSmartlingTranslationApi(False, self.MY_API_KEY, self.MY_PROJECT_ID, proxySettings)
        else:
            self.fapi = SmartlingFileApiFactory().getSmartlingTranslationApiProd(self.MY_API_KEY, self.MY_PROJECT_ID, proxySettings)
        self.uploadData = uploadData
        self.locale = locale
        self.new_name = new_name
        
    def getCredentials(self):
        """ get api key and project id from environment variables
            to set environment variables use command : export SL_API_KEY=******* ; export SL_PROJECT_ID=****** """
        self.MY_API_KEY = os.environ.get('SL_API_KEY', self.MY_API_KEY)
        self.MY_PROJECT_ID = os.environ.get('SL_PROJECT_ID', self.MY_PROJECT_ID)


    def printMarker(self, caption):
        print "--" + caption + "-" * 40

    def test_import(self, name_to_import):
        """ this method tests `import` command """
        self.printMarker("file upload")
        #upload file first to be able upload it's translations later
        resp, code = self.fapi.upload(self.uploadData)
        print resp, code
    
        self.printMarker("files list")
        #list all files to ensure upload worked
        resp, code = self.fapi.list()
        print resp, code

        self.printMarker("importing uploaded")
        old_name = self.uploadData.name
        #set correct uri/name for file to be imported
        self.uploadData.uri = self.uploadData.name
        self.uploadData.name = name_to_import

        #import translations from file
        resp, code = self.fapi.import_call(self.uploadData, self.locale, translationState="READY_FOR_PUBLISH")
        print resp, code

        self.uploadData.name = old_name

        #perform `last_modified` command
        self.printMarker("last modified")
        resp, code = self.fapi.last_modified(self.uploadData.name)
        print "resp.messages=", resp.messages
        print "resp.code=", resp.code
        print "resp.data.items="
        for v in resp.data.items: print v
        
        self.printMarker("delete from server goes here")
        #delete test file imported in the beginning of test
        resp, code = self.fapi.delete(self.uploadData.name)
        print resp, code

    def test(self):
        """ simple illustration for set of API commands: upload, list, status, get, rename, delete """
        self.printMarker("file upload")
        resp, code = self.fapi.upload(self.uploadData)
        print resp, code

        self.printMarker("files list")
        resp, code = self.fapi.list()
        print resp, code

        self.printMarker("file status")
        resp, code = self.fapi.status(self.uploadData.name, self.locale)
        print resp, code

        self.printMarker("file from server goes here")
        resp, code = self.fapi.get(self.uploadData.name, self.locale)
        print resp, code

        self.printMarker("renaming file")
        resp, code = self.fapi.rename(self.uploadData.name, self.new_name)
        print resp, code

        self.printMarker("delete from server goes here")
        resp, code = self.fapi.delete(self.new_name)
        print resp, code

        self.printMarker("doing list again to see if it's deleted")
        resp, code = self.fapi.list()
        print resp, code
class SmartlingApi:
    def __init__(self, apiKey, projectId):
        self.file_api = SmartlingFileApiFactory().getSmartlingTranslationApiProd(apiKey, projectId)

    # Upload a source file
    def uploadFile(self, uploadData):
        self.disableStdOut()
        response, code = self.file_api.upload(uploadData)
        self.enableStdOut()
        if code == 200 and response.code == "SUCCESS":
            return response.data
        else:
            raise IOError("Failed to upload ({0}), caused by: {1}".format(code, self._getMessages(response)))

    # Import a translation
    # ApiResponse: {"response":{"data":{"wordCount":10,"translationImportErrors":[{"contentFileId":238103,"stringHashcode":"851194c88c080f24ef257383841eb757","messages":["Information about import key was not found"],"importKey":null}],"stringCount":5},"code":"SUCCESS","messages":[]}}
    def importFile(self, uploadData, locale, overwrite=False):
        self.disableStdOut()
        response, code = self.file_api.import_call(uploadData, locale, translationState="PUBLISHED", overwrite=str(overwrite).lower())
        self.enableStdOut()
        if code == 200 and response.code == "SUCCESS":
            if response.data.translationImportErrors and len(response.data.translationImportErrors) > 0:
                logging.error("Error Importing translation (%s): %s, Caused by:\n%s",
                              locale,
                              uploadData.uriPath + uploadData.name,
                              self._getStringFromArray(response.data.translationImportErrors))
                raise IOError("Failed to import translation file: {0}".format(uploadData.uriPath + uploadData.name))
            return response.data
        else:
            raise IOError("Failed to import ({0}), caused by: {1}".format(code, self._getMessages(response)))

    # Get a translated files
    def getFile(self, fileUri, locale):
        self.disableStdOut()
        data, code = self.file_api.get(fileUri, locale)
        self.enableStdOut()
        if code == 200:
            return data
        else:
            raise IOError("Failed to get file ({0}): {1}".format(locale, fileUri))

    # Get file status
    # ApiResponse: {"response":{"data":{"fileUri":"common.json","wordCount":9,"fileType":"json","callbackUrl":null,"lastUploaded":"2014-10-30T19:09:36","stringCount":5,"approvedStringCount":0,"completedStringCount":0},"code":"SUCCESS","messages":[]}}
    def getStatus(self, fileUri, locale):
        self.disableStdOut()
        response, code = self.file_api.status(fileUri, locale)
        self.enableStdOut()
        if code == 200 and response.code == "SUCCESS":
            return response.data
        else:
            raise IOError("Failed to get file status ({0}): {1}, caused by: {2}".format(locale, fileUri, self._getMessages(response)))

    # Get list of the project locales
    # ApiResponse: [{'locale': 'de-DE', 'translated': 'Deutsch', 'name': 'German (Germany)'}, {'locale': 'pl-PL', 'translated': 'Polski', 'name': 'Polish (Poland)'}]
    def getProjectLocales(self):
        self.disableStdOut()
        response, code = self.file_api.command(ReqMethod.GET, "/v1/project/locale/list", params={})
        self.enableStdOut()
        if code != 200 or response.code != "SUCCESS":
            raise IOError("Failed to get project locales, caused by: {0}".format(self._getMessages(response)))
        return response.data.locales

    def _getMessages(self, response):
        if response and response.messages:
            return self._getStringFromArray(response.messages)

    def _getStringFromArray(self, array):
        message = ""
        for m in array:
            if len(message) > 0:
                message += "\n"
            message += str(m)
        return message

    def disableStdOut(self):
        self._stdout = sys.stdout
        null = open(os.devnull, 'wb')
        sys.stdout = null

    def enableStdOut(self):
        if self._stdout:
            sys.stdout = self._stdout