# -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2017-04-25 11:36


import os
import uuid
import django.db.models.deletion
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
from django.core import management
from arches.app.models.system_settings import settings

def add_permissions(apps, schema_editor, with_create_permissions=True):
    db_alias = schema_editor.connection.alias
    Group = apps.get_model("auth", "Group")
    Permission = apps.get_model("auth", "Permission")

    read_nodegroup = Permission.objects.get(codename='read_nodegroup', content_type__app_label='models', content_type__model='nodegroup')

    resource_editor_group = Group.objects.using(db_alias).get(name='Resource Editor')
    resource_editor_group.permissions.add(read_nodegroup)
    rdm_admin_group = Group.objects.using(db_alias).get(name='RDM Administrator')
    rdm_admin_group.permissions.add(read_nodegroup)
    app_admin_group = Group.objects.using(db_alias).get(name='Application Administrator')
    app_admin_group.permissions.add(read_nodegroup)
    sys_admin_group = Group.objects.using(db_alias).get(name='System Administrator')
    sys_admin_group.permissions.add(read_nodegroup)
    mobile_project_admin_group = Group.objects.using(db_alias).get(name='Mobile Project Administrator')
    mobile_project_admin_group.permissions.add(read_nodegroup)
    crowdsource_editor_group = Group.objects.using(db_alias).get(name='Crowdsource Editor')
    crowdsource_editor_group.permissions.add(read_nodegroup)
    guest_group = Group.objects.using(db_alias).get(name='Guest')
    guest_group.permissions.add(read_nodegroup)

class Migration(migrations.Migration):

    dependencies = [
        ('models', '0002_40b4'),
    ]

    operations = [
        migrations.RenameField(
            model_name='editlog',
            old_name='attributenodeid',
            new_name='nodegroupid',
        ),
        migrations.AlterField(
            model_name='editlog',
            name='newvalue',
            field=django.contrib.postgres.fields.jsonb.JSONField(blank=True, db_column='newvalue', null=True),
        ),
        migrations.AlterField(
            model_name='editlog',
            name='oldvalue',
            field=django.contrib.postgres.fields.jsonb.JSONField(blank=True, db_column='oldvalue', null=True),
        ),
        migrations.CreateModel(
            name='Geocoder',
            fields=[
                ('geocoderid', models.UUIDField(default=uuid.uuid1, primary_key=True, serialize=False)),
                ('name', models.TextField()),
                ('component', models.TextField()),
                ('api_key', models.TextField(blank=True, null=True)),
            ],
            options={
                'db_table': 'geocoders',
                'managed': True,
            },
        ),
        migrations.RemoveField(
            model_name='graphmodel',
            name='mapfeaturecolor',
        ),
        migrations.RemoveField(
            model_name='graphmodel',
            name='maplinewidth',
        ),
        migrations.RemoveField(
            model_name='graphmodel',
            name='mappointsize',
        ),
        migrations.RunSQL("""
            UPDATE d_data_types
                SET issearchable = true,
                    configcomponent = 'views/components/datatypes/string',
                    configname = 'string-datatype-config'
                WHERE datatype = 'string';
            UPDATE d_data_types
                SET issearchable = true,
                    configcomponent = 'views/components/datatypes/number',
                    configname = 'number-datatype-config'
                WHERE datatype = 'number';
            UPDATE d_data_types
                SET issearchable = true,
                    configcomponent = 'views/components/datatypes/boolean',
                    configname = 'boolean-datatype-config'
                WHERE datatype = 'boolean';
            UPDATE d_data_types
                SET issearchable = true,
                    configcomponent = 'views/components/datatypes/domain-value',
                    configname = 'domain-value-datatype-config'
                WHERE datatype = 'domain-value';
            UPDATE d_data_types
                SET issearchable = true,
                    configcomponent = 'views/components/datatypes/concept',
                    configname = 'concept-datatype-config'
                WHERE datatype = 'concept';
            UPDATE d_data_types
                SET issearchable = true,
                    configcomponent = 'views/components/datatypes/date',
                    configname = 'date-datatype-config'
                WHERE datatype = 'date';
            UPDATE d_data_types
                SET issearchable = true,
                    configcomponent = 'views/components/datatypes/concept',
                    configname = 'concept-datatype-config'
                WHERE datatype = 'concept-list';
            UPDATE d_data_types
                SET issearchable = true,
                    configcomponent = 'views/components/datatypes/domain-value',
                    configname = 'domain-value-datatype-config'
                WHERE datatype = 'domain-value-list';
            UPDATE d_data_types
                SET configcomponent = 'views/components/datatypes/geojson-feature-collection'
                WHERE datatype = 'geojson-feature-collection';
        """, """
            UPDATE d_data_types
                SET issearchable = false,
                    configcomponent = NULL,
                    configname = NULL
                WHERE datatype = 'string';
            UPDATE d_data_types
                SET issearchable = false,
                    configcomponent = NULL,
                    configname = NULL
                WHERE datatype = 'number';
            UPDATE d_data_types
                SET issearchable = false,
                    configcomponent = NULL,
                    configname = NULL
                WHERE datatype = 'boolean';
            UPDATE d_data_types
                SET issearchable = false,
                    configcomponent = NULL,
                    configname = NULL
                WHERE datatype = 'domain-value';
            UPDATE d_data_types
                SET issearchable = false,
                    configcomponent = NULL,
                    configname = NULL
                WHERE datatype = 'concept';
            UPDATE d_data_types
                SET issearchable = false,
                    configcomponent = NULL,
                    configname = NULL
                WHERE datatype = 'date';
            UPDATE d_data_types
                SET issearchable = false,
                    configcomponent = NULL,
                    configname = NULL
                WHERE datatype = 'concept-list';
            UPDATE d_data_types
                SET issearchable = false,
                    configcomponent = NULL,
                    configname = NULL
                WHERE datatype = 'domain-value-list';
            UPDATE d_data_types
                SET configcomponent = 'views/graph/datatypes/geojson-feature-collection',
                WHERE datatype = 'geojson-feature-collection';
        """),

        migrations.RunSQL("""
            INSERT INTO iiif_manifests(id, url) VALUES (public.uuid_generate_v1mc(), 'https://data.getty.edu/museum/api/iiif/249995/manifest.json');
        """, """
            DELETE FROM public.iiif_manifests WHERE url = 'https://data.getty.edu/museum/api/iiif/249995/manifest.json';
        """),
        migrations.RunSQL("""
            INSERT INTO public.relations(relationid, conceptidfrom, conceptidto, relationtype) VALUES (public.uuid_generate_v1mc(), '00000000-0000-0000-0000-000000000004', '00000000-0000-0000-0000-000000000007', 'narrower') ON CONFLICT DO NOTHING;
        """,
        """
            DELETE FROM public.relations WHERE conceptidfrom = '00000000-0000-0000-0000-000000000004' AND conceptidto = '00000000-0000-0000-0000-000000000007' AND relationtype = 'narrower';
        """),
        migrations.RunSQL("""
            INSERT INTO widgets(widgetid, name, component, datatype, defaultconfig)
                VALUES ('10000000-0000-0000-0000-000000000022', 'iiif-widget', 'views/components/widgets/iiif', 'iiif-drawing', '{
                        "placeholder": "",
                        "options": [],
                        "nameLabel": "Name",
                        "typeLabel": "Type"
                    }'
                );
            INSERT INTO widgets(widgetid, name, component, datatype, defaultconfig) VALUES ('10000000-0000-0000-0000-000000000020', 'csv-chart-widget', 'views/components/widgets/csv-chart', 'csv-chart-json', '{"acceptedFiles": "", "maxFilesize": "200"}');
            INSERT INTO d_data_types(datatype, iconclass, modulename, classname, defaultconfig, configcomponent, configname, isgeometric, defaultwidget)
                VALUES ('csv-chart-json', 'fa fa-line-chart', 'datatypes.py', 'CSVChartJsonDataType', null, null, null, FALSE, '10000000-0000-0000-0000-000000000020');
            INSERT INTO d_data_types(datatype, iconclass, modulename, classname, defaultconfig, configcomponent, configname, isgeometric, defaultwidget)
                VALUES ('iiif-drawing', 'fa fa-file-code-o', 'datatypes.py', 'IIIFDrawingDataType', '{"rdmCollection": null}', 'views/components/datatypes/concept', 'concept-datatype-config', FALSE, '10000000-0000-0000-0000-000000000022');
            UPDATE d_data_types SET (modulename, classname) = ('datatypes.py', 'DomainDataType') WHERE datatype = 'domain-value';
            UPDATE d_data_types SET (modulename, classname) = ('datatypes.py', 'DomainListDataType') WHERE datatype = 'domain-value-list';
            """,
            """
            DELETE FROM d_data_types WHERE datatype = 'iiif-drawing';
            DELETE FROM d_data_types WHERE datatype = 'csv-chart-json';
            DELETE FROM widgets WHERE widgetid = '10000000-0000-0000-0000-000000000020';
            DELETE from widgets WHERE widgetid = '10000000-0000-0000-0000-000000000022';
            UPDATE d_data_types SET (modulename, classname) = ('concept_types.py', 'ConceptDataType') WHERE datatype = 'domain-value';
            UPDATE d_data_types SET (modulename, classname) = ('concept_types.py', 'ConceptListDataType') WHERE datatype = 'domain-value-list';
        """),
        migrations.RunSQL("""
            INSERT INTO public.geocoders(geocoderid, name, component, api_key) VALUES ('10000000-0000-0000-0000-010000000000', 'Mapbox', 'views/components/geocoders/mapbox', '');
            INSERT INTO public.geocoders(geocoderid, name, component) VALUES ('10000000-0000-0000-0000-010000000001', 'Mapzen', 'views/components/geocoders/mapzen');
        """,
        """
            DELETE FROM public.geocoders WHERE geocoderid = '10000000-0000-0000-0000-010000000000';
            DELETE FROM public.geocoders WHERE name = 'Mapzen';
        """),
        migrations.RunSQL("""
            UPDATE report_templates SET defaultconfig = '{
                "basemap": "streets",
                "geometryTypes": [{"text":"Point", "id":"Point"}, {"text":"Line", "id":"Line"}, {"text":"Polygon", "id":"Polygon"}],
                "overlayConfigs": [],
                "overlayOpacity": 0.0,
                "geocodeProvider": "10000000-0000-0000-0000-010000000000",
                "zoom": 10,
                "maxZoom": 20,
                "minZoom": 0,
                "centerX": -122.3979693,
                "centerY": 37.79,
                "pitch": 0.0,
                "bearing": 0.0,
                "geocodePlaceholder": "Search",
                "geocoderVisible": true,
                "featureColor": "#FF0000",
                "featureLineWidth": 1,
                "featurePointSize": 3,
                "featureEditingDisabled": true,
                "mapControlsHidden": false
            }' WHERE templateid = '50000000-0000-0000-0000-000000000002';

            UPDATE widgets SET defaultconfig = '{
                    "basemap": "streets",
                    "geometryTypes": [{"text":"Point", "id":"Point"}, {"text":"Line", "id":"Line"}, {"text":"Polygon", "id":"Polygon"}],
                    "overlayConfigs": [],
                    "overlayOpacity": 0.0,
                    "geocodeProvider": "10000000-0000-0000-0000-010000000000",
                    "zoom": 0,
                    "maxZoom": 20,
                    "minZoom": 0,
                    "centerX": 0,
                    "centerY": 0,
                    "pitch": 0.0,
                    "bearing": 0.0,
                    "geocodePlaceholder": "Search",
                    "geocoderVisible": true,
                    "featureColor": "#FF0000",
                    "featureLineWidth": 1,
                    "featurePointSize": 3
                }' WHERE widgetid = '10000000-0000-0000-0000-000000000007';
        """,
        """
            UPDATE report_templates SET defaultconfig = '{
                "basemap": "streets",
                "geometryTypes": [{"text":"Point", "id":"Point"}, {"text":"Line", "id":"Line"}, {"text":"Polygon", "id":"Polygon"}],
                "overlayConfigs": [],
                "overlayOpacity": 0.0,
                "geocodeProvider": "MapzenGeocoder",
                "zoom": 10,
                "maxZoom": 20,
                "minZoom": 0,
                "centerX": -122.3979693,
                "centerY": 37.79,
                "pitch": 0.0,
                "bearing": 0.0,
                "geocodePlaceholder": "Search",
                "geocoderVisible": true,
                "featureColor": null,
                "featureLineWidth": null,
                "featurePointSize": null,
                "featureEditingDisabled": true,
                "mapControlsHidden": false
            }' WHERE templateid = '50000000-0000-0000-0000-000000000002';
            UPDATE widgets SET defaultconfig = '{
                "basemap": "streets",
                "geometryTypes": [{"text":"Point", "id":"Point"}, {"text":"Line", "id":"Line"}, {"text":"Polygon", "id":"Polygon"}],
                "overlayConfigs": [],
                "overlayOpacity": 0.0,
                "geocodeProvider": "MapzenGeocoder",
                "zoom": 0,
                "maxZoom": 20,
                "minZoom": 0,
                "centerX": 0,
                "centerY": 0,
                "pitch": 0.0,
                "bearing": 0.0,
                "geocodePlaceholder": "Search",
                "geocoderVisible": true,
                "featureColor": null,
                "featureLineWidth": null,
                "featurePointSize": null
            }' WHERE widgetid = '10000000-0000-0000-0000-000000000007';
        """),


        ## the following command has to be run after the previous RunSQL commands that update the domain datatype values
        migrations.RunPython(add_permissions,reverse_code=lambda *args,**kwargs: True),
    ]
