#########################################################################
#                                                                       #
#  This file is part of gazix.                                          #
#                                                                       #
#  gazix is free software: you can redistribute it and/or modify        #
#  it under the terms of the GNU General Public License as published by #
#  the Free Software Foundation, either version 3 of the License, or    #
#  (at your option) any later version.                                  #
#                                                                       #
#  gazix is distributed in the hope that it will be useful,             #
#  but WITHOUT ANY WARRANTY; without even the implied warranty of       #
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        # 
#  GNU General Public License for more details.                         #
#                                                                       #
#  You should have received a copy of the GNU General Public License    #
#  along with gazix. If not, see <https://www.gnu.org/licenses/>.       #
#                                                                       #
#########################################################################

#########################################################################
#                                                                       #
#  This file is part of gazix.                                          #
#                                                                       #
#  gazix is free software: you can redistribute it and/or modify        #
#  it under the terms of the GNU General Public License as published by #
#  the Free Software Foundation, either version 3 of the License, or    #
#  (at your option) any later version.                                  #
#                                                                       #
#  gazix is distributed in the hope that it will be useful,             #
#  but WITHOUT ANY WARRANTY; without even the implied warranty of       #
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        #
#  GNU General Public License for more details.                         #
#                                                                       #
#  You should have received a copy of the GNU General Public License    #
#  along with gazix. If not, see <https://www.gnu.org/licenses/>.       #
#                                                                       #
#########################################################################

from .trigger import *
from ..api.gitlab_api_queries import *
from ..arguments.arguments import *
from ..utils.option import *
from ..utils.file import *
from ..api.gitlab_api_job import *

labels_program = "trigger-squidient"
cobertura_job = "run:alya_staging"
cobertura_file = "cobertura.zip"

class TriggerSquidient(Trigger):

    def __init__(self, arguments):
        self._codecoverage = False
        self._cobertura = False
        super().__init__(arguments)
        for i in range(len(arguments)):
            if option(arguments[i], codecoverage):
                self._codecoverage = True
            elif option(arguments[i], cobertura):
                self._cobertura = True


    def process(self):
        r=self.trigger()
        if r != 0:
            exit(r)
        if self._wait :
            if self._codecoverage:
                self.coverage()
            if self._cobertura:
                self.cobertura()
            if self.is_success():
                print("Success!")
                exit(0)
            else:
                print("Failed!")
                exit(1)

    def coverage(self):
        try:
            print("Retrieving code coverage")
            cc = self._queries_wait.get(self._pipeline_object)["coverage"]
            write_text_file("cc.txt", cc)
            print("Code coverage has been found")
        except:
            print("Code coverage is unavailable")

    def cobertura(self):
        try:
            print("Retrieving cobertura files")
            jobs = self._queries_wait.get(self._pipeline_object, "jobs")
            for job in jobs:
                if job["name"] == cobertura_job:
                    job_id = job["id"]
            if job_id == - 1:
                raise Exception
            job = GitlLabAPIJob(job_id)
            self._queries_wait.download_job_artifacts(job, cobertura_file)
            print(command("unzip "+cobertura_file, output=True))
            print(command("ls -R *", output=True))
            print(command("tar -xf reports.tar.gz", output=True))
            print(command("ls -R reports/xml", output=True))

        except:
           print("Cobertura is unavailable")

    def is_success(self):
        return self._queries_wait.get(self._pipeline_object)["status"] == "success"

    def help(self, gazix="", program=""):
        print(gazix + " " + program + " [options]")
        print("\toptions:")
        print("\t-h/--help                Print the help")
        print("\t--gitlab [value]         Gitlab API url of the repository")
        print("\t--token_trigger [value]  Trigger token of the repository")
        print("\t--token_wait [value]     Token of the repository (required for wait, cc and cobertura)")
        print("\t--project [value]        ID of the repository")
        print("\t-v/--var [key]:[value]   Variable to transmit to the pipeline")
        print("\t-r/--ref [value]         Reference of the repository (main, master, etc.)")
        print("\t-cc                      Enable code coverage")
        print("\t--cobertura              Enable cobertura")
        print("\t-w/--wait                Wait for the end of the pipeline execution")
        print("\t-u/--unstable            Unstable mode")
