import shutil
import json
import os

import mysql.connector

import onebet.settings
import mainapp.models


class TeamImage:

    OLD_PATH = os.path.join(
        os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))),
        'bob-prod', 'images', 'team'
    )
    NEW_PATH = os.path.join(
        os.path.dirname(os.path.dirname(__file__)),
        'mainapp', 'static', 'img', 'team'
    )

    @classmethod
    def update_images(cls):
        conn = mysql.connector.connect(
            host=onebet.settings.MYSQL_HOST, port=onebet.settings.MYSQL_PORT, user=onebet.settings.MYSQL_USERNAME,
            password=onebet.settings.MYSQL_PASSWORD, db=onebet.settings.MYSQL_DATABASE
        )
        cursor = conn.cursor()
        cursor.execute("""
            SELECT id, id_sport, gender, names, images
            FROM teams 
            WHERE JSON_CONTAINS_PATH(names, 'one', '$.matchendirect')
            AND JSON_EXTRACT(images, '$.30') NOT LIKE 'h30-default-team.svg%'
        """)

        for row in cursor.fetchall():
            try: 
                team = mainapp.models.Team.objects.get(
                    sport_id=row[1],
                    gender=' MF'.index(row[2]),
                    names__matchendirect=json.loads(row[3])['matchendirect']
                )
            except mainapp.models.Team.DoesNotExist:
                continue
            
            print(f'[+] Copying images for team #{row[0]} => #{team.id}')
            team.images = {
                'H30': f't{team.id}-h30.svg',
                'H50': f't{team.id}-h50.svg',
                'H80': f't{team.id}-h80.svg'
            }

            old_images = json.loads(row[4])
            for size in '30', '50', '80':
                old_path = os.path.join(cls.OLD_PATH, old_images[size].split('?')[0])
                new_path = os.path.join(cls.NEW_PATH, team.images['H'+size])
                shutil.copy2(old_path, new_path)
                team.images['H'+size] += '?t=' + str(int(os.path.getmtime(new_path)))
            team.save()

        cursor.close()
        conn.close()
