# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2019-09-11 07:15
from __future__ import unicode_literals

import django.core.validators
from django.db import migrations, models
import freenasUI.freeadmin.models.fields


def create_smart_alert_service(apps, schema_editor):
    smart = apps.get_model("services.smart").objects.all()[0]
    alertservice = apps.get_model('system.alertservice')
    root_email = apps.get_model('account.bsdusers').objects.filter(bsdusr_username="root")[0].bsdusr_email
    existing_emails = [s.attributes.get("email") or root_email
                       for s in alertservice.objects.filter(type="Mail")]
    emails = [x.strip() for x in smart.smart_email.split(",") if x.strip()]
    for new_email in set(emails) - set(existing_emails):
        as_ = alertservice()
        as_.name = new_email
        as_.type = "Mail"
        as_.attributes = {"email": new_email}
        as_.enabled = True
        as_.level = "WARNING"
        as_.save()


class Migration(migrations.Migration):

    dependencies = [
        ('services', '0035_remove_asigra'),
        ('system', '0039_alerts_classes'),
    ]

    operations = [
        migrations.RunPython(create_smart_alert_service),
        migrations.RemoveField(
            model_name='smart',
            name='smart_email',
        ),
    ]
