import os

from django.contrib.gis.utils import LayerMapping

from ..load import get_processed_data_file
from .models import WaterParcel, waterparcel_mapping


def from_shapefile(transaction_mode='autocommit', **kwargs):
    """
    Load water parcel data into the database from the processed shapefile.
    """
    # Using transaction_mode=autocommit because otherwise LayerMapping gets
    # stuck on a feature and can't commit anything
    filename = os.path.join('water_parcels', 'water_parcels.shp')
    parcel_shp = get_processed_data_file(filename)
    mapping = LayerMapping(WaterParcel, parcel_shp, waterparcel_mapping,
                           transform=True, transaction_mode=transaction_mode)
    mapping.save(**kwargs)


def load(**kwargs):
    from_shapefile(**kwargs)

@@ -117,16 +117,30 @@
 s import
+ WaterAccount,
  WaterPa
@@ -780,20 +780,1036 @@
 shapefile(**kwargs)%0A
+%0A%0Adef fix_water_accounts():%0A    %22%22%22Fix WaterAccount instances that point to old WaterParcels.%22%22%22%0A    old_accounts = WaterAccount.objects.filter(water_parcel__parcelid__isnull=True)%0A    for water_account in old_accounts:%0A        orig_parcel = water_account.water_parcel%0A%0A        try:%0A            # Find new WaterParcel%0A            new_parcel = WaterParcel.objects.get(parcelid=orig_parcel.parcel_id)%0A%0A            # Update new WaterParcel with missing data from old WaterParcel%0A            for field in orig_parcel._meta.fields:%0A                attrname = field.get_attname()%0A                if not getattr(new_parcel, attrname):%0A                    setattr(new_parcel, attrname, getattr(orig_parcel, attrname))%0A            new_parcel.save()%0A%0A            # Point account to new parcel%0A            water_account.water_parcel = new_parcel%0A            water_account.save()%0A        except WaterParcel.DoesNotExist:%0A            print 'Could not find WaterParcel %25s. Moving on.' %25 orig_parcel.parcel_id%0A            continue%0A

Fix WaterAccount instances pointing to old WaterParcels