"""
The MIT License (MIT)

Copyright (c) 2012-2014 Alexander Turkin
Copyright (c) 2014 William Hallatt
Copyright (c) 2015 Jacob Dawid
Copyright (c) 2016 Luca Weiss
Copyright (c) 2017 fbjorn
Copyright (c) 2022 Jakob Wilhelm

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import math
from contextlib import asynccontextmanager
from qgis.PyQt.QtCore import QRect, QTimer, Qt
from qgis.PyQt.QtGui import QColor, QPainter, QPaintEvent, QFont, QFontMetrics
from qgis.PyQt.QtWidgets import QWidget

@asynccontextmanager
async def loading_animation(widget, **kwargs):
    spinner = None
    default_args = {'disableParentWhenSpinning': True, 'radius': 5, 'lines': 20, 'line_length': 5, 'line_width': 1, 'color': (0, 6, 128), 'modality': Qt.WindowModality.WindowModal}
    try:
        spinner = WaitingSpinner(widget, **{**default_args, **kwargs})
        spinner.start()
        yield spinner
    finally:
        if spinner is not None:
            spinner.stop()

class WaitingSpinner(QWidget):

    def __init__(self, parent, centerOnParent=True, disableParentWhenSpinning=False, modality=Qt.WindowModality.NonModal, roundness=100.0, opacity=None, fade=80.0, lines=20, line_length=10, line_width=2, radius=10, speed=math.pi / 2, color=(0, 0, 0), text='', text_color=None, font_size=8):
        super().__init__(parent)
        self._centerOnParent = centerOnParent
        self._disableParentWhenSpinning = disableParentWhenSpinning
        self._color = QColor(*color)
        self._roundness = roundness
        self._minimumTrailOpacity = math.pi
        self._trailFadePercentage = fade
        self._revolutionsPerSecond = speed
        self._numberOfLines = lines
        self._lineLength = line_length
        self._lineWidth = line_width
        self._innerRadius = radius
        self._currentCounter = 0
        self._isSpinning = False
        self._text = text
        self._textColor = QColor(*text_color) if text_color else QColor(*color)
        self._fontSize = font_size
        self._textMargin = 8
        self._timer = QTimer(self)
        self._timer.timeout.connect(self.rotate)
        self.updateSize()
        self.updateTimer()
        self.hide()
        self.setWindowModality(modality)
        self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)

    def paintEvent(self, e: QPaintEvent):
        self.updatePosition()
        painter = QPainter(self)
        painter.fillRect(self.rect(), Qt.GlobalColor.transparent)
        painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
        if self._currentCounter >= self._numberOfLines:
            self._currentCounter = 0
        spinner_diameter = (self._innerRadius + self._lineLength) * 2
        x_offset = (self.width() - spinner_diameter) / 2
        painter.setPen(Qt.PenStyle.NoPen)
        for i in range(self._numberOfLines):
            painter.save()
            painter.translate(x_offset + self._innerRadius + self._lineLength, self._innerRadius + self._lineLength)
            rotateAngle = float(360 * i) / float(self._numberOfLines)
            painter.rotate(rotateAngle)
            painter.translate(self._innerRadius, 0)
            distance = self.lineCountDistanceFromPrimary(i, self._currentCounter, self._numberOfLines)
            color = self.currentLineColor(distance, self._numberOfLines, self._trailFadePercentage, self._minimumTrailOpacity, self._color)
            painter.setBrush(color)
            painter.drawRoundedRect(QRect(0, int(self._lineWidth / 2), self._lineLength, self._lineWidth), self._roundness, self._roundness, Qt.SizeMode.RelativeSize)
            painter.restore()
        if self._text:
            painter.setPen(self._textColor)
            font = QFont()
            font.setPointSize(self._fontSize)
            painter.setFont(font)
            spinner_diameter = (self._innerRadius + self._lineLength) * 2
            text_y = spinner_diameter + self._textMargin
            text_rect = QRect(0, text_y, self.width(), self.height() - text_y)
            painter.drawText(text_rect, Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignTop, self._text)

    def start(self):
        self.updatePosition()
        self._isSpinning = True
        self.show()
        if self.parentWidget and self._disableParentWhenSpinning:
            self.parentWidget().setEnabled(False)
        if not self._timer.isActive():
            self._timer.start()
            self._currentCounter = 0

    def stop(self):
        self._isSpinning = False
        self.hide()
        if self.parentWidget() and self._disableParentWhenSpinning:
            self.parentWidget().setEnabled(True)
        if self._timer.isActive():
            self._timer.stop()
            self._currentCounter = 0

    def setText(self, text):
        self._text = text
        self.updateSize()
        self.update()

    def setTextColor(self, color):
        if isinstance(color, tuple):
            self._textColor = QColor(*color)
        else:
            self._textColor = QColor(color)
        self.update()

    def setFontSize(self, size):
        self._fontSize = size
        self.updateSize()
        self.update()

    def setNumberOfLines(self, lines):
        self._numberOfLines = lines
        self._currentCounter = 0
        self.updateTimer()

    def setLineLength(self, length):
        self._lineLength = length
        self.updateSize()

    def setLineWidth(self, width):
        self._lineWidth = width
        self.updateSize()

    def setInnerRadius(self, radius):
        self._innerRadius = radius
        self.updateSize()

    @property
    def color(self):
        return self._color

    @property
    def roundness(self):
        return self._roundness

    @property
    def minimumTrailOpacity(self):
        return self._minimumTrailOpacity

    @property
    def trailFadePercentage(self):
        return self._trailFadePercentage

    @property
    def revolutionsPersSecond(self):
        return self._revolutionsPerSecond

    @property
    def numberOfLines(self):
        return self._numberOfLines

    @property
    def lineLength(self):
        return self._lineLength

    @property
    def lineWidth(self):
        return self._lineWidth

    @property
    def innerRadius(self):
        return self._innerRadius

    @property
    def isSpinning(self):
        return self._isSpinning

    def setRoundness(self, roundness):
        self._roundness = max(0.0, min(100.0, roundness))

    def setColor(self, color=Qt.GlobalColor.black):
        self._color = QColor(color)

    def setRevolutionsPerSecond(self, revolutionsPerSecond):
        self._revolutionsPerSecond = revolutionsPerSecond
        self.updateTimer()

    def setTrailFadePercentage(self, trail):
        self._trailFadePercentage = trail

    def setMinimumTrailOpacity(self, minimumTrailOpacity):
        self._minimumTrailOpacity = minimumTrailOpacity

    def rotate(self):
        self._currentCounter += 1
        if self._currentCounter >= self._numberOfLines:
            self._currentCounter = 0
        self.update()

    def updateSize(self):
        spinner_size = (self._innerRadius + self._lineLength) * 2
        if self._text:
            font = QFont()
            font.setPointSize(self._fontSize)
            fm = QFontMetrics(font)
            text_width = fm.horizontalAdvance(self._text)
            text_height = fm.height()
            total_width = max(spinner_size, text_width)
            total_height = spinner_size + self._textMargin + text_height
            self.setFixedSize(total_width, total_height)
        else:
            self.setFixedSize(spinner_size, spinner_size)

    def updateTimer(self):
        self._timer.setInterval(int(1000 / (self._numberOfLines * self._revolutionsPerSecond)))

    def updatePosition(self):
        if self.parentWidget() and self._centerOnParent:
            self.move(int(self.parentWidget().width() / 2) - int(self.width() / 2), int(self.parentWidget().height() / 2) - int(self.height() / 2))

    def lineCountDistanceFromPrimary(self, current, primary, totalNrOfLines):
        distance = primary - current
        if distance < 0:
            distance += totalNrOfLines
        return distance

    def currentLineColor(self, countDistance, totalNrOfLines, trailFadePerc, minOpacity, colorinput):
        color = QColor(colorinput)
        if countDistance == 0:
            return color
        minAlphaF = minOpacity / 100.0
        distanceThreshold = int(math.ceil((totalNrOfLines - 1) * trailFadePerc / 100.0))
        if countDistance > distanceThreshold:
            color.setAlphaF(minAlphaF)
        else:
            alphaDiff = color.alphaF() - minAlphaF
            gradient = alphaDiff / float(distanceThreshold + 1)
            resultAlpha = color.alphaF() - gradient * countDistance
            resultAlpha = min(1.0, max(0.0, resultAlpha))
            color.setAlphaF(resultAlpha)
        return color