"""new package versions

Revision ID: 8dfb7c4bfbd7
Revises: 98c04a65df4a
Create Date: 2020-12-21 16:35:33.940460

"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql

# revision identifiers, used by Alembic.
revision = '8dfb7c4bfbd7'
down_revision = '98c04a65df4a'
branch_labels = None
depends_on = None

enum_values = ('hour', 'day', 'month', 'year')


def get_intervaltype():
    if op.get_context().dialect.name == 'postgresql':
        intervaltype = sa.dialects.postgresql.ENUM(
            *enum_values, name='intervaltype', create_type=False
        )
    else:
        intervaltype = sa.Enum(*enum_values, name='intervaltype')  # type: ignore
    return intervaltype


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    intervaltype = get_intervaltype()

    op.drop_table('package_version_metrics')
    op.create_table(
        'aggregated_metrics',
        sa.Column('id', sa.LargeBinary(length=16), nullable=False),
        sa.Column('channel_name', sa.String(), nullable=True),
        sa.Column('platform', sa.String(), nullable=True),
        sa.Column('filename', sa.String(), nullable=True),
        sa.Column('metric_name', sa.String(length=255), nullable=False),
        sa.Column('period', intervaltype, nullable=True),
        sa.Column('count', sa.Integer(), server_default=sa.text('0'), nullable=False),
        sa.Column('timestamp', sa.DateTime(), nullable=False),
        sa.PrimaryKeyConstraint('id'),
    )
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    intervaltype = get_intervaltype()

    op.create_table(
        'package_version_metrics',
        sa.Column(
            'package_version_id',
            postgresql.BYTEA(),
            autoincrement=False,
            nullable=False,
        ),
        sa.Column(
            'metric_name', sa.VARCHAR(length=255), autoincrement=False, nullable=False
        ),
        sa.Column('period', intervaltype, autoincrement=False, nullable=False),
        sa.Column(
            'count',
            sa.INTEGER(),
            server_default=sa.text('0'),
            autoincrement=False,
            nullable=False,
        ),
        sa.Column(
            'timestamp', postgresql.TIMESTAMP(), autoincrement=False, nullable=False
        ),
        sa.ForeignKeyConstraint(
            ['package_version_id'],
            ['package_versions.id'],
            name='package_version_metrics_package_version_id_fkey',
        ),
        sa.PrimaryKeyConstraint(
            'package_version_id',
            'metric_name',
            'period',
            'timestamp',
            name='package_version_metrics_pkey',
        ),
    )
    op.drop_table('aggregated_metrics')
    # ### end Alembic commands ###
