import logging
import requests
from app.models import Project

class DataGetter:
    code_stats = {}
    repos = []

    def fetch(self):
        self.load_repos()
        logging.info("Repos loaded")
        self.load_code_stats()
        logging.info("Code stats loaded")

    def load_repos(self):
        try:
            resp = requests.get("https://git.mootfrost.dev/api/v1/repos/search",
                                params={'limit': 64,
                                        'sort': 'updated',
                                        'order': 'desc'}).json()
        except Exception as e:
            logging.error(f'Error while fetching repos: {e}')
            return

        repos = []
        for repo in resp['data']:
            repos.append(Project(repo["name"], repo["description"], repo["html_url"]))
        self.repos = repos

    def load_code_stats(self) -> dict:
        try:
            resp = requests.get('https://waka.mootfrost.dev/api/compat/wakatime/v1/users/Mootfrost/stats/last_7_days').json()
        except RequestException as e:
            logging.error(f'Error while fetching code stats: {e}')
            return

        code_stats = {}
        for el in resp['data']['languages']:
            hours = el['hours']
            minutes = el['minutes']

            code_stats[el['name']] = ''
            if hours > 0:
                code_stats[el['name']] = declension(hours, 'час', 'часа', 'часов') + ' '
            if minutes > 0:
                code_stats[el['name']] += declension(minutes, 'минуту', 'минуты', 'минут') + ' '
            if code_stats[el['name']] == '':
                code_stats.pop(el['name'])
        self.code_stats = code_stats

__all__ = ['DataGetter']