from typing import List

from aiopg.sa.connection import SAConnection
import sqlalchemy as sa

from src import enitites


metadata = sa.MetaData()


change_record_table = sa.Table(
    'change_records',
    metadata,
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('source_id', sa.Integer, unique=True),
    sa.Column('workflow_id', sa.String),
    sa.Column('workflow_code', sa.String),
    sa.Column('proposal_id', sa.String),
    sa.Column('budget_position_id', sa.Integer),
    sa.Column('budget_position_code', sa.Integer),
    sa.Column('started_at', sa.DateTime),
    sa.Column('resolved_at', sa.DateTime),
    sa.Column('effective_date', sa.DateTime),
    sa.Column('login', sa.String),
    sa.Column('join_at', sa.DateTime),
    sa.Column('staff_id', sa.Integer),
    sa.Column('person_id', sa.Integer),
    sa.Column('ticket', sa.String),
    sa.Column('optional_ticket', sa.String),
    sa.Column('vacancy_id', sa.Integer),
    sa.Column('department_id', sa.Integer),
    sa.Column('hr_product_id', sa.Integer),
    sa.Column('headcount', sa.Integer),
)


class DataswampRegistryRepository(enitites.DataswampRegistryRepositoryInterface):
    def __init__(self, connection: SAConnection):
        self._connection = connection

    async def all_changes(self, from_id: int) -> List[enitites.RegistryChangeEvent]:
        query = change_record_table.select().where(change_record_table.c.id > from_id)
        query = query.order_by(change_record_table.c.id).limit(1000)
        execution_result = await self._connection.execute(query)
        rows = await execution_result.fetchall()
        return [enitites.RegistryChangeEvent(*row.values()) for row in rows]
