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

#    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 3 of the License, or
#    (at your option) any later version.
#
#    This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.

global pyside6_is_installed

try:
    from PySide6.QtWidgets import QCheckBox, QLineEdit, QAbstractItemView, QFileDialog, QSystemTrayIcon, QMenu, QApplication, QInputDialog, QMessageBox
    from PySide6.QtCore import QDir, QTime, QCoreApplication, QRect, QSize, QPoint, QThread, Signal, Qt, QTranslator, QLocale
    from PySide6.QtGui import QFont, QIcon, QStandardItem, QCursor, QAction
    from PySide6 import __version__ as PYQT_VERSION_STR
    from PySide6.QtCore import __version__ as QT_VERSION_STR 
    pyside6_is_installed = True
except:
    from PyQt5.QtWidgets import QCheckBox, QLineEdit, QAbstractItemView, QAction, QFileDialog, QSystemTrayIcon, QMenu, QApplication, QInputDialog, QMessageBox
    from PyQt5.QtCore import QDir, QTime, QCoreApplication, QRect, QSize, QPoint, QThread, Qt, QTranslator, QLocale, QT_VERSION_STR
    from PyQt5.QtGui import QFont, QIcon, QStandardItem, QCursor
    from PyQt5.Qt import PYQT_VERSION_STR
    from PyQt5.QtCore import pyqtSignal as Signal
    pyside6_is_installed = False

from persepolis.scripts.useful_tools import muxer, freeSpace, determineConfigFolder, osAndDesktopEnvironment
from persepolis.scripts.video_finder_progress import VideoFinderProgressWindow
from persepolis.gui.mainwindow_ui import MainWindow_Ui, QTableWidgetItem
from persepolis.scripts.data_base import PluginsDB, PersepolisDB, TempDB
from persepolis.scripts.browser_plugin_queue import BrowserPluginQueue
from persepolis.scripts.after_download import AfterDownloadWindow
from persepolis.scripts.properties import PropertiesWindow
from persepolis.scripts.setting import PreferencesWindow
from persepolis.scripts.progress import ProgressWindow
from persepolis.scripts.play import playNotification
from persepolis.scripts.addlink import AddLinkWindow
from persepolis.scripts.text_queue import TextQueue
from persepolis.scripts.log_window import LogWindow
from persepolis.scripts.update import checkupdate
from persepolis.scripts.shutdown import shutDown
from persepolis.scripts.about import AboutWindow
from persepolis.scripts.bubble import notifySend
from persepolis.scripts import osCommands
from persepolis.scripts import download
from persepolis.scripts import logger
from persepolis.scripts import spider
from persepolis.gui import resources
from persepolis.constants import OS
from functools import partial
from copy import deepcopy
from time import sleep
import urllib.parse
import subprocess
import textwrap
import random
import time
import sys
import os

global youtube_dl_is_installed
try:
    from persepolis.scripts.video_finder_addlink import VideoFinderAddLink
    youtube_dl_is_installed = True
except ModuleNotFoundError:
    # if youtube_dl module is not installed:
    logger.sendToLog(
        "youtube_dl is not installed.", "ERROR")
    youtube_dl_is_installed = False

# CheckVersionsThread thread can change this variable.
global ffmpeg_is_installed
ffmpeg_is_installed = True

# The GID (or gid) is a key to manage each download. Each download will be assigned a unique GID.
# The GID is stored as 64-bit binary value in aria2. For RPC access,
# it is represented as a hex string of 16 characters (e.g., 2089b05ecca3d829).
# Normally, aria2 generates this GID for each download, but the user can
# specify GIDs manually


# shutdown_notification = 0 >> persepolis is running
# 1 >> persepolis is ready for closing(closeEvent  is called)
# 2 >> OK, let's close application!

global shutdown_notification
shutdown_notification = 0

# checking_flag : 0 >> normal situation ;
# 1 >> remove button or delete button pressed or sorting form viewMenu or ... toggled by user ;
# 2 >> check_download_info function is stopping until remove operation done ;
# 3 >> deleteFileAction is done it's job and It is called removeButtonPressed.

global checking_flag
checking_flag = 0

# when rpc connection between persepolis and aria is disconnected >>
# aria2_disconnected = 1
# aria2_disconnected = 0 >> every thing is ok :)
global aria2_disconnected
aria2_disconnected = 0

global aria_startup_answer
aria_startup_answer = None


global button_pressed_counter
button_pressed_counter = 0

global plugin_links_checked
plugin_links_checked = False

# find os platform
os_type, desktop_env = osAndDesktopEnvironment()

# config_folder
config_folder = determineConfigFolder()

do
wnload_info_folder = os.path.join(config_folder, "download_info")


# persepolis tmp folder path
persepolis_tmp = os.path.join(config_folder, 'persepolis_tmp')


# se
e persepolis.py file for show_window_file and plugin_ready
plugin_ready = os.path.join(persepolis_tmp, 'persepolis-plugin-ready')

show_window_file = os.path.join(persepolis_tmp, 'show-window')

# this thread checks ffmpeg availability.
# this thread checks ffmpeg and python and pyqt and qt versions and write them in log file.
# this thread writes osi type and desktop env. in log file.


class CheckVersionsThread(QThread):
    def __init__(self):
        QThread.__init__(self)

    def run(self):
        global ffmpeg_is_installed

        if os_type in OS.UNIX_LIKE:
            ffmpeg_path = 'ffmpeg'

        elif os_type == OS.OSX:

            cwd = sys.argv[0]
            current_directory = os.path.dirname(cwd)
            ffmpeg_path = os.path.join(current_directory, 'ffmpeg')

        elif os_type == OS.WINDOWS:

            cwd = sys.argv[0]
            current_directory = os.path.dirname(cwd)
            ffmpeg_path = os.path.join(current_directory, 'ffmpeg.exe')

        try:
            if os_type == OS.WINDOWS:

                # NO_WINDOW option avoids opening additional CMD in MS Windows.
                NO_WINDOW = 0x08000000
                pipe = subprocess.Popen([ffmpeg_path, '-version'],
                                        stdout=subprocess.PIPE,
                                        stderr=subprocess.PIPE,
                                        stdin=subprocess.PIPE,
                                        shell=False,
                                        creationflags=NO_WINDOW)

            else:
                pipe = subprocess.Popen(
                    [ffmpeg_path, '-version'],
                    stdout=subprocess.PIPE,
                    stdin=subprocess.PIPE,
                    stderr=subprocess.PIPE,
                    shell=False)

            if pipe.wait() == 0:
                ffmpeg_is_installed = True
                ffmpeg_output, error = pipe.communicate()
                ffmpeg_output = ffmpeg_output.decode('utf-8')

            else:
                ffmpeg_is_installed = False
                ffmpeg_output = 'ffmpeg is not installed'
        except:
            ffmpeg_is_installed = False
            ffmpeg_output = 'ffmpeg is not installed'

        # wrap ffmpeg_output with width=70
        wrapper = textwrap.TextWrapper()
        ffmpeg_output = wrapper.fill(ffmpeg_output)

        ffmpeg_output = '\n**********\n'\
            + str(ffmpeg_output)\
            + '\n**********\n'

        logger.sendToLog(ffmpeg_output, "INFO")

        # log python version
        logger.sendToLog('python version: '
                         + str(sys.version))

        # log qt version
        logger.sendToLog('QT version: '
                         + str(QT_VERSION_STR))
        # log pyqt version
        if pyside6_is_installed:
            madule_str = 'PySide version: '
        else:
            madule_str = 'PyQt version: '

        logger.sendToLog(madule_str
                         + str(PYQT_VERSION_STR))

       