#
# Copyright (c) Daniel Sheffield 2021 - 2023
#
# All rights reserved
#
# THIS SOFTWARE IS PROVIDED AS IS WITHOUT WARRANTY
import numpy as np
class Rating():
    def __init__(self, text_fields):
        self.text_fields = text_fields
        self.size = 14

    def update_rating(self, _avg, _min, _max, unit, price=None, quantity=None):
        if None in (_avg, _min, _max):
            self.text_fields['rating'].set_text('')
            self.text_fields['spread'].set_text('')
            self.text_fields['marker'].set_text('')
            return
        current = None if None in (price, quantity or None) else float(price/quantity)
        
        chars = ['|', *['-']*(self.size - 2), '|' ]
        rating = [' ']*len(chars)
        _min, _max = min(_min, current or _min), max(_max, current or _max)
        ls = np.linspace(_min, _max, len(chars))
        if current is not None and _avg is not None:
            if current <= _avg:
                p = 'badge_good'
            else:
                p = 'badge_bad'
        else:
            p = 'badge_neutral'

        for idx, (e, a) in enumerate(zip(ls, ls[1:])):
            if e <= _avg <= a:
                for c, (_idx,_) in zip(''.join(list(f'{_avg:>5.2f}')[:idx+2]), filter(lambda x: idx-2 < x[0] and x[0]>0, enumerate(chars))):
                    chars[_idx] = (p, c)

            if current is not None and e <= current < a:
                rating[idx] = '^'

        chars[0] = '|'
        chars[-1] = '|'

        if current is not None:
            self.text_fields['rating'].set_text(
                f"{current:>5.2f}/{unit} {current/_avg - 1:>4.0%}"
            )

        if _min != _max:
            if current == _max:
                rating[-1] = '^'
            self.text_fields['marker'].set_text(f"{' '*5}{''.join(rating)}{' '*5}")
            self.text_fields['spread'].set_text([
                f"{_min:>5.2f}", ('badge_highlight', chars), f"{_max:<5.2f}"
            ])
        else:
            self.text_fields['spread'].set_text('')
            self.text_fields['marker'].set_text('')

