#!/usr/bin/env python3
# -*- coding: utf8 -*-

import sys
import csv
from pprint import pprint
from dbfread import DBF


class GTIN(object):
    '''
    from http://stackoverflow.com/questions/35552374/
    by Andronaute
    '''

    def __init__(self, barcode=''):
        self.barcode = barcode

    def __checkDigit(self, digits):
        total = sum(digits) + sum([d*2 for d in digits[-1::-2]])
        return (10 - (total % 10)) % 10

    def validateCheckDigit(self, barcode=''):
        barcode = (barcode if barcode else self.barcode)
        if len(barcode) in (8, 12, 13, 14) and barcode.isdigit():
            digits = [int(s) for s in barcode]
            checkDigit = self.__checkDigit(digits[0:-1])
            return checkDigit == digits[-1]
        return False

    def addCheckDigit(self, barcode=''):
        barcode = (barcode if barcode else self.barcode)
        if len(barcode) in (7, 11, 12, 13) and barcode.isdigit():
            digits = [int(s) for s in barcode]
            return barcode + str(self.__checkDigit(digits))
        return ''


range = {'1': '78968962', '2': '78996188'}

f = open('DIS_BAT.DBF', 'r')

table = DBF('DIS_BAT.DBF')
pprint(table)
writer = csv.writer(sys.stdout)

writer.writerow(table.field_names)
for record in table:
    # pass
    if record['B_PROD'] == '640':
        # pprint(record)
        # print(range[record['B_RANGE']])
        ean13_ = range[record['B_RANGE']] + record['B_CODBAR']
        ean13 = GTIN(ean13_).addCheckDigit()
        prod = record['B_PROD']
        cor = record['B_COR']
        tam = record['B_TAM']
        print('{}.{}.{}: {}'.format(prod, cor, tam, ean13))
        # sys.exit(9)

@@ -1107,16 +1107,18 @@
 6188'%7D%0A%0A
+# 
 f = open
@@ -1152,16 +1152,26 @@
  = DBF('
+./scripts/
 DIS_BAT.
@@ -1176,16 +1176,18 @@
 T.DBF')%0A
+# 
 pprint(t
@@ -1192,16 +1192,19 @@
 (table)%0A
+%0A# 
 writer =
@@ -1227,17 +1227,18 @@
 stdout)%0A
-%0A
+# 
 writer.w
@@ -1299,16 +1299,18 @@
 pass%0A   
+ #
  if reco
@@ -1332,16 +1332,48 @@
  '640':%0A
+    if record%5B'B_ATIV'%5D == 'S':%0A
         
@@ -1646,16 +1646,18 @@
  print('
+--
 %7B%7D.%7B%7D.%7B%7D
@@ -1679,30 +1679,335 @@
 od, 
-cor, tam, ean13
+tam, cor, ean13))%0A        print(%22UPDATE basi_010 c SET c.CODIGO_BARRAS = '%7B%7D' %22%0A              %22WHERE c.CODIGO_VELHO = 'PA%7B%7D.%7B%7D.%7B%7D' %22%0A              %22AND c.NIVEL_ESTRUTURA = 1 AND c.GRUPO_ESTRUTURA %3C '99999' %22%0A              %22AND c.CODIGO_BARRAS IS NULL;%22.format(ean13, prod, tam, cor
 ))%0A    
+ 
+   # sys.exit(9)%0A    # pprint(record)%0A
     

generate sql