# PamhyrID.py -- Pamhyr
# Copyright (C) 2024-2025  INRAE
#
# 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 <https://www.gnu.org/licenses/>.

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

import logging

from tools import trace, timer

logger = logging.getLogger()


class PamhyrID(object):
    _pamhyr_id_cnt = 0

    def __init__(self, id: int = -1, **kwargs):
        super(PamhyrID, self).__init__(**kwargs)

        self._pamhyr_id = self.get_new_pamhyr_id(id)

    @classmethod
    def get_new_pamhyr_id(cls, id):
        pid = int(id)

        if pid < 0:
            pid = PamhyrID._pamhyr_id_cnt

        PamhyrID._pamhyr_id_cnt = max(
            id + 1,
            PamhyrID._pamhyr_id_cnt + 1
        )

        return pid

    @property
    def id(self):
        return self._pamhyr_id

    @property
    def pamhyr_id(self):
        return self._pamhyr_id

    @classmethod
    def update_db_add_pamhyr_id(cls, execute, table,
                                data=None):
        execute(
            f"ALTER TABLE {table} " +
            f"ADD COLUMN pamhyr_id INTEGER NOT NULL DEFAULT -1"
        )

        id2pid = cls.update_db_add_pamhyr_id_init_id2pid(table, data)
        rows = execute(f"SELECT id FROM {table}")

        if rows is None:
            return True

        for row in rows:
            id = row[0]
            pid = cls.get_new_pamhyr_id(-1)

            id2pid[table][id] = pid

            execute(
                f"UPDATE {table} " +
                f"SET pamhyr_id = {pid} " +
                f"WHERE id = {id}"
            )

        return True

    @classmethod
    def update_db_add_pamhyr_id_init_id2pid(cls, table, data):
        id2pid = {}
        if "id2pid" in data:
            id2pid = data["id2pid"]
        else:
            data["id2pid"] = id2pid

        if table not in id2pid:
            id2pid[table] = {}

        return id2pid

    @classmethod
    def create_db_add_pamhyr_id(cls):
        return "pamhyr_id INTEGER NOT NULL"
