# -*- coding: utf-8 -*-

"""
/***************************************************************************
 GeoINCRA
                                 A QGIS plugin
 Georreferenciamento de Imóveis Rurais
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2022-02-13
        copyright            : (C) 2022 by Tiago Prudencio e Leandro França
        email                : contato@geoone.com.br
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program 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 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
"""

__author__ = 'Tiago Prudencio e Leandro França'
__date__ = '2022-02-13'
__copyright__ = '(C) 2022 by Tiago Prudencio e Leandro França'

from qgis.PyQt.QtCore import QCoreApplication
from qgis.core import (QgsProcessingException,
                       QgsProcessingAlgorithm,
                       QgsProcessingParameterFileDestination)
from qgis.PyQt.QtGui import QIcon
from GeoINCRA.images.Imgs import *
import os
import shutil
import requests


class getSpreadsheet(QgsProcessingAlgorithm):

    OUTPUT = 'OUTPUT'

    def tr(self, string):
        return QCoreApplication.translate('Processing', string)

    def createInstance(self):
        return getSpreadsheet()

    def name(self):
        return 'modeloplanilha'

    def displayName(self):
        return self.tr('Baixar planilha ODS do SIGEF')

    def group(self):
        return self.tr(self.groupId())

    def groupId(self):
        return ''

    def icon(self):
        return QIcon(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'images/geoincra_pb.png'))
    
    def tags(self):
        return 'GeoOne,GeoRural,INCRA,Sigef,planilha,ODS,baixar,download,baixar,regularização,fundiária'.split(',')

    def shortHelpString(self):
        txt = "Gera uma planilha ODS vazia para preenchimento com os dados gerados no TXT."

        footer = '''<div>
                      <div align="center">
                      <img style="width: 100%; height: auto;" src="data:image/jpg;base64,'''+ INCRA_GeoOne +'''
                      </div>
                      <div align="right">
                      <p align="right">
                      <a href="https://geoone.com.br/pvgeoincra2/"><span style="font-weight: bold;">Conheça o curso de GeoINCRA no QGIS</span></a>
                      </p>
                      <p align="right">
                      <a href="https://portal.geoone.com.br/m/lessons/georreferenciamento-de-imveis-rurais-com-o-plugin-geoincra-1690158094835"><span style="font-weight: bold;">Acesse seu curso na GeoOne</span></a>
                      </p>
                      <a target="_blank" rel="noopener noreferrer" href="https://geoone.com.br/"><img height="80" title="GeoOne" src="data:image/png;base64,'''+ GeoOne +'''"></a>
                      <p><i>"Mapeamento automatizado, fácil e direto ao ponto é na GeoOne!"</i></p>
                      </div>
                    </div>'''
        return txt + footer

    def initAlgorithm(self, config=None):

        self.addParameter(
            QgsProcessingParameterFileDestination(
                self.OUTPUT,
                self.tr('Caminho para salvar a planilha ODS'),
                self.tr('OpenDocument files (*.ods)')
            )
        )


    def processAlgorithm(self, parameters, context, feedback):
        """
        Here is where the processing itself takes place.
        """
        output = self.parameterAsOutputLayer(
            parameters,
            self.OUTPUT,
            context)
        if not output:
            raise QgsProcessingException(self.invalidSourceError(parameters, self.OUTPUT))


        fonte = os.path.dirname(__file__) + "/shp" + "/sigef_planilha_modelo_1.3_rc5.ods"

        try:
            shutil.copy(fonte, output)

        except:
            try:
                # Fazendo a requisição GET para obter o conteúdo do arquivo
                url = "https://sigef.incra.gov.br/static/sigef_planilha_modelo_1.3_rc5.ods"
                response = requests.get(url)
                # Verificando se a requisição foi bem-sucedida
                if response.status_code == 200:
                    # Escrevendo o conteúdo do arquivo em um arquivo local
                    with open(output, 'wb') as f:
                        f.write(response.content)
                else:
                    feedback.pushInfo("Falha ao baixar o arquivo. Status code: {}".format(response.status_code))
            except Exception as e:
                feedback.pushInfo("Ocorreu um erro: {}".format(e))

        # Check for cancelation
        if feedback.isCanceled():
            return {}

        try:
            os.popen(output)
        except:
            feedback.pushInfo('Abra o arquivo de saída na pasta {}'.format(output))

        return {self.OUTPUT: output}
