# -*- coding: utf-8 -*-

from django.db.utils import IntegrityError
from django.core.management.base import BaseCommand, CommandError
from django.utils.timezone import now

from accounting_core.models import AccountingYear, Account, AccountCategory, CostCenter
from units.models import Unit

import datetime
import pytz
import json
import sys


class Command(BaseCommand):
    help = 'Import financesglob'

    def handle(self, *args, **options):

        data = json.loads(sys.stdin.read())
        mainant = now()


        paris_tz = pytz.timezone("Europe/Paris")

        for year_data in data['year']:
            ay = AccountingYear(name=year_data['name'], status='3_archived')
            years = ay.name.split('-')
            ay.start_date = paris_tz.localize(datetime.datetime.strptime('{}-08-01 00:00:00'.format(years[0]), '%Y-%m-%d %H:%M:%S'))
            ay.end_date = paris_tz.localize(datetime.datetime.strptime('{}-08-01 00:00:00'.format(years[1]), '%Y-%m-%d %H:%M:%S')) - datetime.timedelta(seconds=1)

            if mainant < ay.end_date and mainant > ay.start_date:
                ay.status = '1_active'

            ay.save()
            print "(+)", ay

            for tcb_data in data['typeCompteBilan']:
                ac = AccountCategory(name=tcb_data['name'], description=tcb_data['description'], accounting_year=ay)
                ac.save()
                print "  (+)", ac

                for ct_data in tcb_data['compte_types']:
                    sub_ac = AccountCategory(name=ct_data['name'], description=ct_data['description'], parent_hierarchique=ac, accounting_year=ay)
                    sub_ac.save()
                    print "    (+)", sub_ac

            print "*" * 20

            for num_data in year_data['numeros']:
                cc = CostCenter(name=num_data['name'], account_number=num_data['account_number'], description=num_data['description'], accounting_year=ay)

                try:
                    cc.unit = Unit.objects.get(name=num_data['unit_name'])
                except:
                    cc.unit = Unit.objects.get(pk=1)
                    print u"Cost Center {} from Year {} has no Unit. Set to Comité de Direction. Edit manually?".format(cc.name, ay)
                cc.save()
                print "  (+)", cc

            print "*" * 20

            for cc_data in year_data['compte_cats']:
                try:
                    parent = AccountCategory.objects.get(accounting_year=ay, name=cc_data['compte_type_name'])
                    leaf_ac = AccountCategory(name=cc_data['name'], parent_hierarchique=parent, accounting_year=ay)
                    leaf_ac.save()
                    print "  (+)", leaf_ac
                except:
                    print "Parent not found !!"

                for comp_data in cc_data['comptes']:
                    acc = Account(name=comp_data['name'], account_number=comp_data['account_number'], description=comp_data['description'], category=leaf_ac, accounting_year=ay)
                    if comp_data['ndfComs']:
                        acc.visibility = 'all'
                    elif comp_data['ndfMaster']:
                        acc.visibility = 'cdd'
                    else:
                        acc.visibility = 'root'
                    try:
                        acc.save()
                        print "    (+)", acc
                    except IntegrityError:
                        print u"Duplicate with name {}, number {} and year {}".format(acc.name, acc.account_number, ay)

@@ -614,16 +614,25 @@
       ay
+, created
  = Accou
@@ -640,16 +640,38 @@
 tingYear
+.objects.get_or_create
 (name=ye
@@ -689,17 +689,34 @@
 me'%5D
-, 
+)%0A            ay.
 status
-=
+ = 
 '3_a
@@ -723,17 +723,16 @@
 rchived'
-)
 %0A       
@@ -1180,32 +1180,60 @@
       ay.save()%0A
+            if created:%0A    
             prin
@@ -1316,16 +1316,25 @@
       ac
+, created
  = Accou
@@ -1339,24 +1339,46 @@
 ountCategory
+.objects.get_or_create
 (name=tcb_da
@@ -1438,32 +1438,33 @@
 unting_year=ay)%0A
+%0A
                 
@@ -1463,26 +1463,32 @@
         
-ac.save()%0A
+if created:%0A    
         
@@ -1597,16 +1597,25 @@
   sub_ac
+, created
  = Accou
@@ -1620,24 +1620,46 @@
 ountCategory
+.objects.get_or_create
 (name=ct_dat
@@ -1741,32 +1741,33 @@
 unting_year=ay)%0A
+%0A
                 
@@ -1774,22 +1774,24 @@
     
-sub_ac.save()%0A
+if created:%0A    
     
@@ -1927,16 +1927,25 @@
       cc
+, created
  = CostC
@@ -1949,16 +1949,38 @@
 stCenter
+.objects.get_or_create
 (name=nu
@@ -2420,32 +2420,65 @@
       cc.save()%0A
+%0A                if created:%0A    
                 
@@ -2736,16 +2736,25 @@
  leaf_ac
+, created
  = Accou
@@ -2763,16 +2763,38 @@
 Category
+.objects.get_or_create
 (name=cc
@@ -2848,32 +2848,33 @@
 unting_year=ay)%0A
+%0A
                 
@@ -2881,23 +2881,24 @@
     
-leaf_ac.save()%0A
+if created:%0A    
     
@@ -3085,16 +3085,25 @@
      acc
+, created
  = Accou
@@ -3104,16 +3104,38 @@
  Account
+.objects.get_or_create
 (name=co
@@ -3585,32 +3585,72 @@
      acc.save()%0A
+                        if created:%0A    
                 
@@ -3777,50 +3777,31 @@
 ame 
-%7B%7D, number %7B%7D and year %7B%7D%22.format(acc.name
+%22, acc.name, %22 number %22
 , ac
@@ -3818,12 +3818,25 @@
 number, 
+%22 and year %22, 
 ay
-)
 %0A

improve import