# -*- coding: utf-8 -*-
import time
import requests

# pylint: disable=missing-docstring,invalid-name


class TGReleaseExport(object):

    REQUESTS_VERIFY = True

    def __init__(self, url, authKey): # <1>
        '''
        Constructor.
        @param url: URL of test.guide instance
        @type url: unicode
        @param authKey: authentication key for accessing API
        @type authKey: unicode
        '''
        self.apiUrl = url + '/api/'
        self.authKey = authKey

    def exportReleaseAsExcel(self, releaseId, projectId, targetFile): # <2>
        '''
        Export the release as XLSX file.
        @param releaseId: ID of the release
        @type releaseId: int
        @param projectId: ID of the project the release belongs to
        @type projectId: int
        @param targetFile: Path to target Excel file.
        '''
        tagSetId = self._getTagSetId(releaseId)
        taskId = self._startExport(tagSetId, projectId)

        self._waitUntilExportDone(taskId)
        self._downloadExportedFile(taskId, targetFile)

    def _getTagSetId(self, releaseId):
        headers = {
            'Accept': 'application/json',
            'TestGuide-AuthKey': self.authKey
        }
        endpoint = self.apiUrl + "releases/" + str(releaseId)

        print(f'Querying release {releaseId} for TagSet ID...')
        response = requests.get(endpoint, headers=headers, verify=self.REQUESTS_VERIFY)
        tagSetId = response.json().get("testCaseTagSetId")
        print(f'TagSet ID is  {tagSetId}.')

        return tagSetId

    def _startExport(self, tagSetId, projectId):
        headers = {
            'Accept': 'application/json',
            'TestGuide-AuthKey': self.authKey
        }
        endpoint = self.apiUrl + "report/testCaseExecutions/export"
        queryString = {'projectId' : projectId}

        exportFilter = {'testCaseTagSetId': tagSetId}

        print('Starting export of Excel file...')
        response = requests.post(endpoint,
                                    headers=headers,
                                    params=queryString,
                                    json=exportFilter,
                                    verify=self.REQUESTS_VERIFY)
        taskId = response.json().get("taskId")
        print(f'Export task ID is {taskId}.')

        return taskId

    def _waitUntilExportDone(self, taskId):
        headers = {
            'Accept': 'application/json',
            'TestGuide-AuthKey': self.authKey
        }
        endpoint = self.apiUrl + "report/testCaseExecutions/export/" + taskId + "/status"
        while True:
            response = requests.get(endpoint, headers=headers, verify=self.REQUESTS_VERIFY)
            jsonResponse = response.json()
            done = jsonResponse.get("done")
            if done:
                print('Export task is finished.')
                break
            else:
                print(f'Export task is not done yet... Progress: {jsonResponse.get("progressinfo")}.')
                time.sleep(1)

    def _downloadExportedFile(self, taskId, targetFile):
        headers = {
            'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'TestGuide-AuthKey': self.authKey
        }
        endpoint = self.apiUrl + "report/testCaseExecutions/export/" + taskId + "/download"
        response = requests.get(endpoint, headers=headers, verify=self.REQUESTS_VERIFY)
        with open(targetFile, 'wb') as f:
            f.write(response.content)
        print(f'Excel file was written to {targetFile}')


if __name__ == '__main__':
    myUurl = "https://localhost:8443"
    myAuthKey = "sJfRTfI=.2NlWQb0F0v7vWr8Jb9ZExqwGDTypF1Q8G5M3-eYZGx0="

    myReleaseId = 14
    myProjectId = 1
    myTargetFile = "myExcelFile.xlsx"

    exporter = TGReleaseExport(myUurl, myAuthKey)
    exporter.exportReleaseAsExcel(myReleaseId, myProjectId, myTargetFile)