'''
ARCHES - a program developed to inventory and manage immovable cultural heritage.
Copyright (C) 2013 J. Paul Getty Trust and World Monuments Fund

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''

import copy
from arches.app.models import models
from arches.app.models.tile import Tile
from arches.app.models.card import Card
from django.utils.translation import ugettext as _
from arches.app.utils.betterJSONSerializer import JSONSerializer, JSONDeserializer

class Form(object):
    def __init__(self, resourceid=None, formid=None, user=None):
        self.forms = []
        self.tiles = {}
        self.blanks = {}

        if resourceid or formid:
            self.load(resourceid, formid=formid, user=user)

    def load(self, resourceid, formid=None, user=None):
        tiles = Tile.objects.filter(resourceinstance_id=resourceid).order_by('sortorder')
        # for tile in Tile.objects.filter(resourceinstance_id=resourceid).order_by('sortorder'):
        #     if tile.filter(user):
        #         tiles.append(tile)
        print JSONSerializer().serializeToPython(tiles)

        # get the form and card data
        if formid is not None:
            form = models.Form.objects.get(pk=formid)
            formxcards = form.formxcard_set.all()
            form_obj = {
                'id': form.pk,
                'title': form.title,
                'subtitle': form.subtitle
            }
            form_obj['cardgroups'] = []
            for formxcard in formxcards:
                card = Card.objects.get(cardid=formxcard.card_id)
                if user:
                    card.filter_by_perm(user, 'read_nodegroup')
                card_obj = JSONSerializer().serializeToPython(card)
                form_obj['cardgroups'].append(card_obj)
            self.forms = [form_obj]


        # get the actual tile data
        for form in self.forms:
            for cardgroup in form['cardgroups']:
                self.tiles[cardgroup['nodegroup_id']] = JSONSerializer().serializeToPython(tiles.filter(nodegroup_id=cardgroup['nodegroup_id']))

                if len(self.tiles[cardgroup['nodegroup_id']]) > 0:
                    for parentTile in self.tiles[cardgroup['nodegroup_id']]:
                        parentTile['tiles'] = {}
                        for card in cardgroup['cards']:
                            parentTile['tiles'][card['nodegroup_id']] = []
                        for tile in JSONSerializer().serializeToPython(tiles.filter(parenttile_id=parentTile['tileid'])):
                            try:
                                parentTile['tiles'][str(tile['nodegroup_id'])].append(tile)
                            except:
                                pass


        # get the blank tile data
        for form in self.forms:
            for cardgroup in form['cardgroups']:
                # add blank parent tile
                parentTile = JSONSerializer().serializeToPython(Tile())
                parentTile['tileid'] = ''
                parentTile['parenttile_id'] = None
                parentTile['resourceinstance_id'] = resourceid
                parentTile['nodegroup_id'] = cardgroup['nodegroup_id']
                parentTile['tiles'] = {}
                parentTile['data'] = {}
                for widget in cardgroup['widgets']:
                    parentTile['data'][widget['node_id']] = None

                # add a blank tile for the cardgroup
                self.blanks[parentTile['nodegroup_id']] = [parentTile]

                for card in cardgroup['cards']:
                    # make a blank tile
                    tile = JSONSerializer().serializeToPython(Tile())
                    tile['tileid'] = ''
                    tile['parenttile_id'] = None # parentTile
                    tile['resourceinstance_id'] = resourceid
                    tile['nodegroup_id'] = card['nodegroup_id']
                    tile['tiles'] = {}
                    tile['data'] = {}
                    for widget in card['widgets']:
                        tile['data'][widget['node_id']] = None

                    if(card['cardinality'] == '1'):
                        parentTile['tiles'][card['nodegroup_id']] = [tile]
                    else:
                        parentTile['tiles'][card['nodegroup_id']] = []

                    # add a blank tile for each card
                    self.blanks[tile['nodegroup_id']] = [tile]

    # def filter(self, user):
    #     for tiles in self.tiles.itervalues:
    #         for parentTile in tiles:
    #             if user.has_perm('read_nodegroup', parentTile.nodegroup_id)
@@ -1452,16 +1452,245 @@
        #
+ print JSONSerializer().serializeToPython(len(tiles))%0A        # tiles2 = %5B%5D%0A        # tiles3 = Tile.objects.filter(resourceinstance_id=resourceid).filter_by_perm(user=user, perm='read_nodegroup').order_by('sortorder')%0A        # #
  for til
@@ -1774,24 +1774,26 @@
 ):%0A        #
+ #
      if tile
@@ -1799,21 +1799,47 @@
 e.filter
-(user
+_by_perm(user, 'read_nodegroup'
 ):%0A     
@@ -1838,24 +1838,26 @@
 ):%0A        #
+ #
          til
@@ -1858,16 +1858,17 @@
    tiles
+2
 .append(
@@ -1880,16 +1880,18 @@
 %0A       
+ #
  print J
@@ -1924,21 +1924,27 @@
 oPython(
+len(
 tiles
+3)
 )%0A%0A     
@@ -3397,15 +3397,78 @@
     
-try:%0A  
+# only append tiles that havn't been filtered out by user permissions%0A
     
@@ -3491,38 +3491,19 @@
         
-  parentTile%5B'tiles'%5D%5B
+if 
 str(tile
@@ -3523,95 +3523,124 @@
 d'%5D)
-%5D.append(tile)%0A                            except:%0A                                pass
+ in parentTile%5B'tiles'%5D:%0A                                parentTile%5B'tiles'%5D%5Bstr(tile%5B'nodegroup_id'%5D)%5D.append(tile)
 %0A%0A%0A 

clean up code and remove unneeded comments, re #1636