# -*- 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.core import (QgsProcessingException,
                       QgsProcessingAlgorithm,
                       QgsProcessingParameterFileDestination)
from qgis.PyQt.QtCore import QCoreApplication, QUrl
from qgis.PyQt.QtGui import QIcon, QDesktopServices
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('a. Baixar planilha ODS do SIGEF')

    def group(self):
        return self.tr('3. 📋 Preenchimento da Planilha ODS')

    def groupId(self):
        return 'preenchimento_planilha_ods'

    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 exportados com a ferramenta TXT para planilha ODS."

        footer = '''<div>
                      <div align="center">
                      <a target="_blank" rel="noopener noreferrer" href="https://geoone.com.br/pvgeoincra/"><img title="Inscreva-se no curso de GeoINCRA" style="width: 100%; height: auto;" src="'''+ os.path.join(os.path.dirname(os.path.dirname(__file__)), 'images/INCRA_GeoOne.jpg') +'''"></a>
                      </div>
                      <div align="right">
                      <p align="right">
                      <a href="https://geoone.com.br/pvgeoincra/"><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/geoincra?classId=2230"><span style="font-weight: bold;">Acesse a aula sobre esta ferramenta no curso de GeoINCRA no GeoOne</span></a>
                      </p>
                      <a target="_blank" rel="noopener noreferrer" href="https://geoone.com.br/"><img title="GeoOne" width="280"  src="'''+ os.path.join(os.path.dirname(os.path.dirname(__file__)), 'images/GeoOne.png') +'''"></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.4_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.4_rc5.ods"
                response = requests.get(url, timeout=30)
                # 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:
            QDesktopServices.openUrl(QUrl.fromLocalFile(output))
        except:
            feedback.pushInfo('Abra o arquivo de saída na pasta {}'.format(output))

        return {self.OUTPUT: output}
