# The MIT License (MIT)

# Copyright (c) 2014-2015 CNRS

# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


import ConfigParser
from camomile import Camomile

if __name__ == '__main__':
    # read config
    Config = ConfigParser.ConfigParser()
    Config.read("config.ini")

    server = Config.get('mainSection', 'url')+":"+Config.get('mainSection', 'port')
    userAdmin = Config.get('userSection', 'userAdmin')
    pwdAdmin = Config.get('userSection', 'pwdAdmin')

    client = Camomile(server)
    client.login(userAdmin, pwdAdmin)

    
    ans = raw_input("\nWrite 'delete' to delete annotations starting with 'DELETE__' (or press enter to continue): ")
    
    count = 0
    if(ans == "delete"):
        print "\n\tdeleting..."
        for a in client.getAnnotations():
            if 'DELETE__' in a.data:
                client.deleteAnnotation(a._id)
                count += 1
        print "\n\t%d annotations deleted" % count

    
    count = 0
    for l in client.getLayers():
        # if "annotateur" in l.name:
        print l.name
        annotations = client.getAnnotations(l._id)
        print('annotations : %d' % len(annotations))

        # tmp = [[(u'start', a['fragment']['start']), (u'end', a['fragment']['end']), (u'data', a['data'])] for a in annotations]
        # tmp = []
        # for a in annotations:
        #     tmp.append({'start': a['fragment']['start'], 'end': a['fragment']['end'], u'data': a['data']})

        tmp = [{'start': a['fragment']['start'], 'end': a['fragment']['end'], u'data': a['data'], 'id_medium': a['id_medium']} for a in annotations]

        cleaned = [dict(t) for t in set([tuple(d.items()) for d in tmp])]

        seen = set()
        doublons = []
        indices = []
        for i in range(0, len(tmp)):
            t = tuple(tmp[i].items())
            if t not in seen:
                seen.add(t)
            else:
                doublons.append(tmp[i])
                indices.append(i)

        print('annotations cleaned : %d' % len(cleaned))
        print('doublons : %d\n' % len(doublons))
        print('indices : %d\n' % len(indices))

        count += len(cleaned)

        for i in range(0, len(indices)):
            data = "DELETE__%s" % annotations[i].data
            client.updateAnnotation(annotations[i]._id, data=data)

        # print "\nannotations:\n\n"
        # for x in sorted(tmp, key=lambda k: k['start']):
        #     print x

        # print "\ncleaned:\n\n"

        # for x in sorted(cleaned, key=lambda k: k['start']):
        #     print x

    print "\n\nComputing grand total..."
    print "\nTotal annotations: \t\t%d" % len(client.getAnnotations())
    print "Total annotations cleaned: \t%d" % count


@@ -1546,421 +1546,34 @@
     
-ans = raw_input(%22%5CnWrite 'delete' to delete annotations starting with 'DELETE__' (or press enter to continue): %22)%0A    %0A    count = 0%0A    if(ans == %22delete%22):%0A        print %22%5Cn%5Ctdeleting...%22%0A        for a in client.getAnnotations():%0A            if 'DELETE__' in a.data:%0A                client.deleteAnnotation(a._id)%0A                count += 1%0A        print %22%5Cn%5Ct%25d annotations deleted%22 %25 count%0A%0A    %0A    count = 0
+count = 0%0A    deleted = 0%0A
 %0A   
@@ -2677,24 +2677,25 @@
 blons))%0A
+%0A
         
 print('i
@@ -2690,56 +2690,38 @@
     
-print('indices : %25d%5Cn' %25 len(indices)
+count += len(cleaned
 )%0A
-%0A
         
 coun
@@ -2712,37 +2712,39 @@
 ed)%0A        
-count
+deleted
  += len(
 cleaned)%0A%0A  
@@ -2731,23 +2731,24 @@
  += len(
-cleaned
+doublons
 )%0A%0A     
@@ -2763,30 +2763,15 @@
  in 
-range(0, len(
 indices
-))
 :%0A  
@@ -2779,16 +2779,18 @@
         
+ #
  data = 
@@ -2835,24 +2835,26 @@
         
+ #
  client.
 updateAn
@@ -2849,11 +2849,11 @@
 ent.
-upd
+cre
 ateA
@@ -2862,16 +2862,143 @@
 otation(
+layer=l._id, medium=annotations%5Bi%5D.id_medium, fragment=annotations%5Bi%5D.fragment, data=data)%0A            client.deleteAnnotation(
 annotati
@@ -3007,27 +3007,16 @@
 s%5Bi%5D._id
-, data=data
 )%0A%0A     
@@ -3243,24 +3243,414 @@
    print x%0A%0A
+%0A%0A    ans = raw_input(%22%5CnWrite 'delete' to delete annotations starting with 'DELETE__' (or press enter to continue): %22)%0A%0A    if(ans == %22delete%22):%0A        print %22%5Cn%5Ctdeleting...%22%0A        for a in client.getAnnotations():%0A            if 'DELETE__' in a.data:%0A                client.deleteAnnotation(a._id)%0A                deleted += 1%0A        print %22%5Cn%5Ct%25d annotations deleted%22 %25 count%0A%0A    %0A
     print %22%5C
@@ -3792,18 +3792,72 @@
 d: %5Ct%25d%22 %25 count
+%0A    print %22Total annotations deleted: %5Ct%25d%22 %25 deleted
 %0A%0A

version ok