"""Peewee migrations -- 001_MAIN.py.

Some examples (model - class or model name)::

    > Model = migrator.orm['model_name']            # Return model in current state by name

    > migrator.sql(sql)                             # Run custom SQL
    > migrator.python(func, *args, **kwargs)        # Run python code
    > migrator.create_model(Model)                  # Create a model (could be used as decorator)
    > migrator.remove_model(model, cascade=True)    # Remove a model
    > migrator.add_fields(model, **fields)          # Add fields to a model
    > migrator.change_fields(model, **fields)       # Change fields
    > migrator.remove_fields(model, *field_names, cascade=True)
    > migrator.rename_field(model, old_field_name, new_field_name)
    > migrator.rename_table(model, new_table_name)
    > migrator.add_index(model, *col_names, unique=False)
    > migrator.drop_index(model, *col_names)
    > migrator.add_not_null(model, *field_names)
    > migrator.drop_not_null(model, *field_names)
    > migrator.add_default(model, field_name, default)

"""

import datetime as dt
import peewee as pw
from peewee_migrate import Migrator
from decimal import ROUND_HALF_EVEN

try:
    import playhouse.postgres_ext as pw_pext
except ImportError:
    pass

SQL = pw.SQL


def migrate(migrator: Migrator, database, fake=False, **kwargs):
    """Write your migrations here."""

    @migrator.create_model
    class AuditedModel(pw.Model):
        id = pw.AutoField()
        audit_changed_by = pw.TextField(null=True)
        audit_changed_at = pw.IntegerField(constraints=[SQL("DEFAULT 0")], default=0)

        class Meta:
            table_name = "auditedmodel"

    @migrator.create_model
    class BaseModel(pw.Model):
        id = pw.AutoField()

        class Meta:
            table_name = "basemodel"

    @migrator.create_model
    class Order(pw.Model):
        id = pw.AutoField()
        hidden = pw.BooleanField(constraints=[SQL("DEFAULT False")], default=False)
        audit_changed_by = pw.TextField(null=True)
        audit_changed_at = pw.IntegerField(constraints=[SQL("DEFAULT 0")], default=0)
        customer = pw.TextField(null=True)
        construction_site = pw.TextField(null=True)
        volume = pw.DoubleField(null=True)
        comment = pw.TextField(null=True)
        auto_number = pw.IntegerField()
        without_water = pw.BooleanField(constraints=[SQL("DEFAULT False")], default=False)
        temperature = pw.DoubleField(null=True)
        status = pw.IntegerField(constraints=[SQL("DEFAULT 0")], default=0)
        t = pw.IntegerField()
        r_name = pw.TextField()
        r_recipe_class = pw.TextField()
        r_description = pw.TextField(null=True)
        r_comment = pw.TextField(null=True)
        r_consistency_class = pw.TextField(null=True)
        r_batch_volume_limit = pw.DoubleField(null=True)
        r_lift_pour_duration = pw.DoubleField(null=True)
        r_lift_semi_pour_duration = pw.DoubleField(null=True)
        r_mixer_semi_opening_duration = pw.DoubleField(null=True)
        r_mixer_opening_duration = pw.DoubleField(null=True)
        r_mixing_duration = pw.DoubleField(null=True)
        r_k_value = pw.DoubleField(null=True)
        r_k_ratio = pw.DoubleField(null=True)
        r_number = pw.TextField(null=True)
        r_d_max = pw.TextField(null=True)
        r_cl_content = pw.TextField(null=True)

        class Meta:
            table_name = "order"

    @migrator.create_model
    class Batch(pw.Model):
        id = pw.AutoField()
        order = pw.ForeignKeyField(backref='batches', column_name='order_id', field='id', model=migrator.orm['order'], on_delete='CASCADE')
        filename = pw.TextField(null=True)
        volume = pw.DoubleField(null=True)
        batch_number = pw.IntegerField(null=True)
        batch_count = pw.IntegerField(null=True)
        production_start = pw.IntegerField(null=True)
        production_end = pw.IntegerField(null=True)
        mixing_duration = pw.DoubleField(null=True)
        consistency = pw.DoubleField(null=True)
        additional_water = pw.DoubleField(null=True)
        water_correction_rq = pw.DoubleField(null=True)
        water_correction_e1 = pw.DoubleField(null=True)
        water_temperature_calculated = pw.DoubleField(null=True)
        continuous_mode = pw.IntegerField(null=True)
        water_temperature = pw.DoubleField(null=True)
        moisture_rq = pw.DoubleField(null=True)
        moisture_e2 = pw.DoubleField(null=True)
        production_mode_e1 = pw.TextField(null=True)
        production_mode_e2 = pw.TextField(null=True)

        class Meta:
            table_name = "batch"

    @migrator.create_model
    class Material(pw.Model):
        id = pw.AutoField()
        type = pw.TextField()
        name = pw.TextField(unique=True)
        long_name = pw.TextField(null=True, unique=True)
        unit = pw.TextField()
        comment = pw.TextField(null=True)

        class Meta:
            table_name = "material"

    @migrator.create_model
    class OrderMaterial(pw.Model):
        id = pw.AutoField()
        type = pw.TextField()
        name = pw.TextField()
        long_name = pw.TextField(null=True)
        unit = pw.TextField()
        comment = pw.TextField(null=True)
        material = pw.ForeignKeyField(backref='orders', column_name='material_id', field='id', model=migrator.orm['material'], null=True, on_delete='SET NULL')
        sequence_number = pw.IntegerField()
        order = pw.ForeignKeyField(backref='materials', column_name='order_id', field='id', model=migrator.orm['order'], on_delete='CASCADE')
        amount = pw.DoubleField()
        delay = pw.DoubleField()

        class Meta:
            table_name = "ordermaterial"

    @migrator.create_model
    class BatchMaterial(pw.Model):
        id = pw.AutoField()
        batch = pw.ForeignKeyField(backref='materials', column_name='batch_id', field='id', model=migrator.orm['batch'], on_delete='CASCADE')
        material = pw.ForeignKeyField(backref='consumptions', column_name='material_id', field='id', model=migrator.orm['ordermaterial'], on_delete='CASCADE')
        consumption_recipe = pw.DoubleField(null=True)
        consumption_rq = pw.DoubleField(null=True)
        consumption_e1 = pw.DoubleField(null=True)
        silo_major_rq = pw.IntegerField(null=True)
        silo_minor_rq = pw.IntegerField(null=True)
        humidity_rq = pw.IntegerField(null=True)
        internal_humidity_rq = pw.IntegerField(null=True)
        density_rq = pw.DoubleField(null=True)
        temperature_rq = pw.DoubleField(null=True)
        bin_rq = pw.IntegerField(null=True)
        delay_rq = pw.DoubleField(null=True)
        silo_major_e1 = pw.IntegerField(null=True)
        silo_minor_e1 = pw.IntegerField(null=True)
        humidity_e1 = pw.IntegerField(null=True)

        class Meta:
            table_name = "batchmaterial"

    @migrator.create_model
    class Car(pw.Model):
        id = pw.AutoField()
        hidden = pw.BooleanField(constraints=[SQL("DEFAULT False")], default=False)
        registration_number = pw.TextField()
        driver = pw.TextField(null=True)
        driver_contact = pw.TextField(null=True)
        operator = pw.TextField(null=True)
        car_type = pw.IntegerField(constraints=[SQL("DEFAULT 0")], default=0)
        comment = pw.TextField(null=True)

        class Meta:
            table_name = "car"

    @migrator.create_model
    class ConstructionSite(pw.Model):
        id = pw.AutoField()
        hidden = pw.BooleanField(constraints=[SQL("DEFAULT False")], default=False)
        name = pw.TextField()
        address = pw.TextField(null=True)
        city = pw.TextField(null=True)
        zip = pw.TextField(null=True)
        phone = pw.TextField(null=True)
        distance = pw.IntegerField(null=True)

        class Meta:
            table_name = "constructionsite"

    @migrator.create_model
    class Customer(pw.Model):
        id = pw.AutoField()
        hidden = pw.BooleanField(constraints=[SQL("DEFAULT False")], default=False)
        name = pw.TextField()
        address = pw.TextField(null=True)
        city = pw.TextField(null=True)
        zip = pw.TextField(null=True)
        phone = pw.TextField(null=True)
        fax = pw.TextField(null=True)
        company_id = pw.TextField(null=True)
        vat_id = pw.TextField(null=True)
        payment_type = pw.IntegerField(constraints=[SQL("DEFAULT 0")], default=0)
        comment = pw.TextField(null=True)

        class Meta:
            table_name = "customer"

    @migrator.create_model
    class Defaults(pw.Model):
        id = pw.AutoField()
        name = pw.TextField()
        batch_volume_limit = pw.DoubleField()
        lift_pour_duration = pw.DoubleField()
        lift_semi_pour_duration = pw.DoubleField()
        k_value = pw.DoubleField()
        k_ratio = pw.DoubleField()
        mixing_duration = pw.DoubleField()
        mixer_semi_opening_duration = pw.DoubleField()
        mixer_opening_duration = pw.DoubleField()
        consistency = pw.TextField()

        class Meta:
            table_name = "defaults"

    @migrator.create_model
    class Recipe(pw.Model):
        id = pw.AutoField()
        name = pw.TextField()
        recipe_class = pw.TextField()
        description = pw.TextField(null=True)
        comment = pw.TextField(null=True)
        consistency_class = pw.TextField(null=True)
        batch_volume_limit = pw.DoubleField(null=True)
        lift_pour_duration = pw.DoubleField(null=True)
        lift_semi_pour_duration = pw.DoubleField(null=True)
        mixer_semi_opening_duration = pw.DoubleField(null=True)
        mixer_opening_duration = pw.DoubleField(null=True)
        mixing_duration = pw.DoubleField(null=True)
        k_value = pw.DoubleField(null=True)
        k_ratio = pw.DoubleField(null=True)
        number = pw.TextField(null=True)
        d_max = pw.TextField(null=True)
        cl_content = pw.TextField(null=True)
        defaults = pw.ForeignKeyField(backref='recipes', column_name='defaults_id', field='id', model=migrator.orm['defaults'], null=True, on_delete='SET NULL')

        class Meta:
            table_name = "recipe"

    @migrator.create_model
    class Contract(pw.Model):
        id = pw.AutoField()
        hidden = pw.BooleanField(constraints=[SQL("DEFAULT False")], default=False)
        name = pw.TextField()
        site = pw.ForeignKeyField(backref='contracts', column_name='site_id', field='id', model=migrator.orm['constructionsite'], on_delete='RESTRICT')
        customer = pw.ForeignKeyField(backref='contracts', column_name='customer_id', field='id', model=migrator.orm['customer'], on_delete='RESTRICT')
        recipe = pw.ForeignKeyField(backref='contracts', column_name='recipe_id', field='id', model=migrator.orm['recipe'], null=True, on_delete='RESTRICT')
        vehicle = pw.ForeignKeyField(backref='contracts', column_name='vehicle_id', field='id', model=migrator.orm['car'], null=True, on_delete='RESTRICT')
        default_volume = pw.DoubleField(null=True)

        class Meta:
            table_name = "contract"

    @migrator.create_model
    class Delivery(pw.Model):
        id = pw.AutoField()
        t = pw.IntegerField()
        car_registration_number = pw.TextField(null=True)
        car_driver = pw.TextField(null=True)
        car_driver_contact = pw.TextField(null=True)
        car_operator = pw.TextField(null=True)
        order = pw.ForeignKeyField(backref='deliveries', column_name='order_id', field='id', model=migrator.orm['order'], on_delete='CASCADE')

        class Meta:
            table_name = "delivery"

    @migrator.create_model
    class HiddeableModel(pw.Model):
        id = pw.AutoField()
        hidden = pw.BooleanField(constraints=[SQL("DEFAULT False")], default=False)

        class Meta:
            table_name = "hiddeablemodel"

    @migrator.create_model
    class RecipeMaterial(pw.Model):
        sequence_number = pw.AutoField()
        recipe = pw.ForeignKeyField(backref='materials', column_name='recipe_id', field='id', model=migrator.orm['recipe'], on_delete='CASCADE')
        material = pw.ForeignKeyField(backref='recipes', column_name='material_id', field='id', model=migrator.orm['material'], on_delete='RESTRICT')
        amount = pw.DoubleField()
        delay = pw.DoubleField()

        class Meta:
            table_name = "recipematerial"

    @migrator.create_model
    class RecipeProduction(pw.Model):
        id = pw.AutoField()
        recipe = pw.ForeignKeyField(backref='productions', column_name='recipe_id', field='id', model=migrator.orm['recipe'], on_delete='CASCADE', unique=True)
        sample_period_days = pw.IntegerField(null=True)
        sample_period_volume = pw.DoubleField(null=True)
        sample_last_volume = pw.DoubleField(constraints=[SQL("DEFAULT 0")], default=0)
        sample_last_t = pw.IntegerField(constraints=[SQL("DEFAULT 0")], default=0)
        volume_total = pw.DoubleField(constraints=[SQL("DEFAULT 0")], default=0)

        class Meta:
            table_name = "recipeproduction"

    @migrator.create_model
    class Sample(pw.Model):
        id = pw.AutoField()
        audit_changed_by = pw.TextField(null=True)
        audit_changed_at = pw.IntegerField(constraints=[SQL("DEFAULT 0")], default=0)
        recipe = pw.ForeignKeyField(backref='samples', column_name='recipe_id', field='id', model=migrator.orm['recipe'], on_delete='RESTRICT')
        t = pw.IntegerField()
        volume = pw.DoubleField(constraints=[SQL("DEFAULT 0")], default=0)
        comment = pw.TextField(null=True)

        class Meta:
            table_name = "sample"

    @migrator.create_model
    class Setup(pw.Model):
        id = pw.AutoField()
        company_name = pw.TextField()
        company_address = pw.TextField(null=True)
        company_zip = pw.TextField(null=True)
        company_city = pw.TextField(null=True)
        company_id = pw.TextField(null=True)
        company_vat_id = pw.TextField(null=True)
        company_legal = pw.TextField(null=True)
        facility_name = pw.TextField(null=True)
        facility_address = pw.TextField(null=True)
        facility_zip = pw.TextField(null=True)
        facility_city = pw.TextField(null=True)
        certification_text = pw.TextField(null=True)
        order_num_series = pw.IntegerField(constraints=[SQL("DEFAULT 1")], default=1)

        class Meta:
            table_name = "setup"

    @migrator.create_model
    class StockMovement(pw.Model):
        id = pw.AutoField()
        material = pw.ForeignKeyField(backref='stock_movements', column_name='material_id', field='id', model=migrator.orm['material'], on_delete='CASCADE')
        amount = pw.DoubleField()
        t = pw.IntegerField()
        comment = pw.TextField(null=True)

        class Meta:
            table_name = "stockmovement"

    @migrator.create_model
    class User(pw.Model):
        id = pw.AutoField()
        username = pw.TextField(unique=True)
        password = pw.TextField()
        can_edit_users = pw.BooleanField(constraints=[SQL("DEFAULT False")], default=False, null=True)

        class Meta:
            table_name = "user"



def rollback(migrator: Migrator, database, fake=False, **kwargs):
    """Write your rollback migrations here."""

    migrator.remove_model('user')

    migrator.remove_model('stockmovement')

    migrator.remove_model('setup')

    migrator.remove_model('sample')

    migrator.remove_model('recipeproduction')

    migrator.remove_model('recipematerial')

    migrator.remove_model('hiddeablemodel')

    migrator.remove_model('delivery')

    migrator.remove_model('contract')

    migrator.remove_model('recipe')

    migrator.remove_model('defaults')

    migrator.remove_model('customer')

    migrator.remove_model('constructionsite')

    migrator.remove_model('car')

    migrator.remove_model('batchmaterial')

    migrator.remove_model('ordermaterial')

    migrator.remove_model('material')

    migrator.remove_model('batch')

    migrator.remove_model('order')

    migrator.remove_model('basemodel')

    migrator.remove_model('auditedmodel')
