# -*- coding: utf-8 -*-
"""
/***************************************************************************
 TopoMaps
                                 A QGIS plugin
 .....Description
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2024-11-11
        git sha              : $Format:%H$
        copyright            : (C) 2024 by ShingoNagano
        email                : shingosnaganon@.gmail.com
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/
"""
from time import time
from qgis.PyQt.QtCore import QCoreApplication
from qgis.PyQt.QtCore import QSettings
from qgis.PyQt.QtCore import QTranslator
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction
from qgis.core import Qgis
from qgis.core import QgsApplication, QgsMessageLog

from .resources import *
from .apps.message import msg
from .topo_maps_dialog import TopoMapsDialog
from .topo_maps_dialog import GenerateMapTask
import os.path


class TopoMaps:
    """QGIS Plugin Implementation."""
    MESSAGE_CATEGORY = 'TopoMaps Plugin'

    def __init__(self, iface):
        self.iface = iface
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        if locale == 'ja':
            locale_path = os.path.join(
                self.plugin_dir,
                'i18n',
                'topo_maps_dlg_ja.qm'.format(locale)
            )
        else:
            locale_path = os.path.join(
                self.plugin_dir,
                'i18n',
                'topo_maps_dlg_en.qm'.format(locale)
            )
        
        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)

        self.actions = []
        self.menu = self.tr(u'&TopoMaps')

        self.first_start = None

    def tr(self, message):
        return QCoreApplication.translate('TopoMaps', message)

    def add_action(
        self,
        icon_path,
        text,
        callback,
        enabled_flag=True,
        add_to_menu=True,
        add_to_toolbar=True,
        status_tip=None,
        whats_this=None,
        parent=None
    ):
        icon = QIcon(icon_path)
        action = QAction(icon, text, parent)
        action.triggered.connect(callback)
        action.setEnabled(enabled_flag)

        if status_tip is not None:
            action.setStatusTip(status_tip)

        if whats_this is not None:
            action.setWhatsThis(whats_this)

        if add_to_toolbar:
            # Adds plugin icon to Plugins toolbar
            self.iface.addToolBarIcon(action)

        if add_to_menu:
            self.iface.addPluginToMenu(
                self.menu,
                action)

        self.actions.append(action)

        return action

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""
        DIR_NAME = os.path.join(os.path.dirname(__file__), 'views')
        icon_path = os.path.join(DIR_NAME, "icon.png")
        self.add_action(
            icon_path,
            text=self.tr(u'TopoMaps'),
            callback=self.run,
            parent=self.iface.mainWindow()
        )

        # will be set False in run()
        self.first_start = True

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(
                self.tr(u'&TopoMaps'),
                action)
            self.iface.removeToolBarIcon(action)


    def run(self):
        """Run method that performs all the real work"""

        # Create the dialog with elements (after translation) and keep reference
        # Only create GUI ONCE in callback, so that it will only load when the plugin is started
        if self.first_start == True:
            self.first_start = False
            self.dlg = TopoMapsDialog()
            self.dlg.pushBtn_Execute.clicked.connect(self.run_generate_topo_map)
            self.dlg.finished.connect(self.on_dialog_closed)

        # show the dialog
        self.dlg.show()
        # tasked = self.dlg.pushBtn_Execute.clicked.connect(self.dlg.execute_alg)
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            pass

    def run_generate_topo_map(self):
        """
        ## Summary
            微地形図を作成するタスクを実行する
        Returns:
            bool: タスクが実行されたかどうか
        """
        input_file_path = self.dlg.get_input_file_path()
        output_spec = self.dlg.get_output_spec()
        input_is_ok = msg.check_input_file_path(input_file_path)
        output_is_ok = msg.check_output_file_path(
            output_spec.output_file_path,
            output_spec.sample_only,
        )
        if all([input_is_ok, output_is_ok]):
            QgsMessageLog.logMessage("run_generate_topo_map called", "TopoMaps Plugin", Qgis.Warning)
            self.dlg.setEnabled(False)
            self.time = time()
            self.task = GenerateMapTask(self.dlg, self.generate_topo_map_completed)
            QgsApplication.taskManager().addTask(self.task)
            msg.run_task(self.MESSAGE_CATEGORY)
            return True
        return False
    
    def generate_topo_map_completed(self, task):
        """
        ## Summary
            微地形図の作成タスクが完了したときの処理
        Args:
            task : 微地形図の作成タスク
        """
        if task.new_dst:
            self.new_dst = task.new_dst
            msg.created_infomation(self.MESSAGE_CATEGORY, self.new_dst)
            output_spec = self.dlg.get_output_spec()
            if output_spec.sample_only:
                # サンプルのみの場合は出力ファイルを指定しなくともよい
                self.dlg.show_sample_dst(self.new_dst)
            else:
                # 出力を書く####################################################
                self.new_dst.save_dst(output_spec.output_file_path)
                self.new_dst = None
                if output_spec.add_project:
                    self.dlg.add_lyr(
                        output_spec.output_file_path, 
                        self.dlg.get_style_name()
                    )
                
            computing = round(time() - self.time, 3)
            msg.computing_time(self.MESSAGE_CATEGORY, computing)
            msg.finished_msg(self.MESSAGE_CATEGORY)
        self.dlg.setEnabled(True)

    def on_dialog_closed(self):
        """
        ## Summary
            ダイアログが閉じられたときの処理
        """
        self.first_start = True