import pytesseract
import PIL.Image
import re
import base64
import json
import sys

base64_string = sys.argv[1]
base64_bytes = base64_string.encode("ascii")
sample_string_bytes = base64.b64decode(base64_bytes) 
sample_string = sample_string_bytes.decode("ascii")
json_str = json.loads(sample_string)

img_dir_path="ScanedImagesTemp/"
text_path="text_data/"

word_name="Applicant Name"
word_chassis="Chassis No"
word_engin="Engine No"
word_sale_amount="Sale Amount"
word_hypo="Hypothecation"
word_name2="Son/"
word_YOMfg="Month/"
word_ins_date="valid from"

img_path=img_dir_path+json_str['dis_img']

myconfig = r"--psm 6 --oem 3 hocr"
image=PIL.Image.open(img_path)
text = pytesseract.image_to_string(image,config=myconfig)
#print(text)
file = open(text_path+"d.txt", 'w')
file.write(text)
file.close()

iimg_path=img_dir_path+json_str['inv_img']
imyconfig = r"--psm 6 --oem 3 hocr"
iimage=PIL.Image.open(iimg_path)
itext = pytesseract.image_to_string(iimage,config=imyconfig)
ifile = open(text_path+"i.txt", 'w')
ifile.write(itext)
ifile.close()

ifile1 = open(text_path+"i1.txt", 'w')
ifile1.write(itext)
ifile1.close()

file = open(text_path+"d.txt", 'r')
Lines = file.readlines()

name_line=chassis_line=engin_line=sale_amount_line=hypo_line=name_line2=YOMfg_line=ins_date_line=sale_amount=""

for line in Lines:
    if word_name in line:
        name_line=re.sub(' +', ' ',line)
    if word_chassis in line:
        chassis_line=line
    if word_engin in line:
        engin_line=line
    if word_sale_amount in line:
        sale_amount_line=line
    if word_hypo in line:
        hypo_line=line
    if word_name2 in line:
        name_line2=re.sub(' +', ' ',line)
    if word_YOMfg in line:
        YOMfg_line=re.sub(' +', ' ',line)
    if word_ins_date in line:
        ins_date_line=re.sub(' +', ' ',line)

try:        
    '''temp_name=name_line.split("Name:",1)[1]
    if not temp_name:
        temp_name=name_line.split("Name",1)[1]'''
    temp_name=re.split('Name |Name:', name_line)[1]
    temp_name_first = re.sub(r'[^a-zA-Z]', '', temp_name)
    name=temp_name_first.strip()
    #name=temp_name.strip()
except IndexError:
    is_ok = False
    name="Not Found"

try:        
    temp_name2=re.split('of |of:', name_line2)[1]
    temp_name_last = re.sub(r'[^a-zA-Z]', '', temp_name2)
    name2=temp_name_last.strip()
    #name2=temp_name2.strip()
except IndexError:
    name2=""

try:        
    temp_YOMfg=re.split('Manuf |Manuf: |Manuf.', YOMfg_line)[1]
    temp_YOMfg=re.split('/',temp_YOMfg)[1]
    YOMfg=temp_YOMfg.strip()
except IndexError:
    YOMfg="Not Found"

try:        
    temp_ins_date=re.split('valid from', ins_date_line)[1]
    temp_ins_date1=re.split('to',temp_ins_date)[0]
    ins_date=temp_ins_date1.strip()
except IndexError:
    ins_date=""

try:
    #temp_chassis=re.split('No |No: |No.', chassis_line)[1]
    temp_chassis=chassis_line.split("No:",1)[1]
    chassis1=temp_chassis.strip()
    chassis2=re.sub(r'[^a-zA-Z0-9]', '', chassis1)
    chassis=chassis2.replace(" ", "")
except IndexError:
    is_ok = False
    chassis="Not Found"

try:
    #temp_engin=engin_line.split("No:",1)[1]
    temp_engin=re.split('No |No: |No.', engin_line)[1]
    temp_engin1=temp_engin.split()[0]
    if len(temp_engin1)<10:
        temp_engin1=temp_engin.split()[0]+temp_engin.split()[1]
    #else:
    temp_engin2=temp_engin1.strip()
    #print(temp_engin2)
    engin=temp_engin2.replace(" ", "")
    engin=temp_engin2.replace(".", "")
except IndexError:
    is_ok = False
    engin="Not Found"

try:
    temp_sale_amount=sale_amount_line.split("Rs.",1)[1]
    temp_sale_amount1=temp_sale_amount.split()[0]
    sale_amount=''.join([n for n in temp_sale_amount1.strip() if n.isdigit()])
    sale_amount_found_comma=format(int(sale_amount),",")
except IndexError:
    is_ok = False
    sale_amount_found_comma="Not Found"

temp_hypo1=""
if(hypo_line!=""):
    if "Details" in hypo_line:
        temp_hypo=hypo_line.split("Details:",1)[1]
        temp_hypo1=temp_hypo.split(",")[0]
    else:
        temp_hypo1="Not Found"
hypo=temp_hypo1.strip()

# print(name)
# print(chassis)
# print(engin)
# print(sale_amount)
# print(hypo)

# print("-----------------------------------------------------------")

iword_name="CUSTOMER NAME"
iword_chassis="CHASSIS"
iword_engin = ["ENGINE NO", "ENGINENO"]
iword_sale_amount=sale_amount_found_comma
iword_hypo="Hypo"

ifile1 = open(text_path+"i1.txt", 'r')
iLines = ifile1.readlines()

iname_line=ichassis_line=iengin_line=isale_amount_line=ihypo_line=""

for iline in iLines:
    iline=re.sub(';', ':',iline)
    iline=re.sub('-', ':',iline)
    iline=re.sub(r'(?:(?<=:) | (?=:))','',iline)
    if iword_name in iline:
        iname_line=iline
    if iword_chassis in iline:
        ichassis_line=iline
    if any(x in iline for x in iword_engin):
        iengin_line=iline
    if iword_sale_amount in iline:
        isale_amount_line=iline
    if iword_hypo in iline:
        ihypo_line=iline

iname_line=re.sub(r'[^A-Za-z0-9 ,:-]+', '', iname_line)
try:
    itemp_name=iname_line.split("MODEL",1)[0]
    iname=itemp_name.strip()
except IndexError:
    is_ok = False
    iname="Not Found"+iname_line
#print(iname)

ichassis_line=re.sub(r'[^A-Za-z0-9 ,:-]+', '', ichassis_line)
try:
    itemp_chassis=ichassis_line.split("CHASSIS",1)[1]
    ichassis=itemp_chassis.strip()
except IndexError:
    is_ok = False
    ichassis="Not Found"
#print(ichassis)

iengin_line=re.sub(r'[^A-Za-z0-9 ,:-]+', '', iengin_line)
try:
    itemp_engin=iengin_line.split("ENGINE",1)[1]
    iengin=itemp_engin.strip()
except IndexError:
    is_ok = False
    iengin="Not Found"
#print(iengin)

isale_amount=iword_sale_amount

# iitemp_hypo=ihypo_line.split("Hypo:",1)[1]
# iihypo=iitemp_hypo.strip()

iihypo=ihypo_line.strip()


# print(iname)
# print(ichassis)
# print(iengin)
# print(isale_amount)
# print(iihypo)

# print("-----------------------------------------------------------")
ifile = open(text_path+"i.txt", 'r')
itext=ifile.read()
name_found,chassis_found,engin_found,hypo_found,sale_amount_found = False, False, False, False, False
if name in itext: 
   name_found=True
if chassis in itext: 
   chassis_found=True
if engin in itext: 
   engin_found=True

ihypo_len=len(iihypo)   
if(hypo!=""):
    if hypo in itext: 
        hypo_found=True
else:
    if len(iihypo) < 4:
        hypo_found=True
        
if sale_amount_found_comma in itext: 
   sale_amount_found=True
   
# print(name_found)
# print(chassis_found)
# print(engin_found)
# if(hypo!=""):
    # print(hypo_found)
# else:
    # print("Hypo not found in disclaimer")
# print(sale_amount_found)

json_data='{"dname":"'+name+'","dchassis":"'+chassis+'","dengin":"'+engin+'","dsale_amount":"'+sale_amount+'","dhypo":"'+hypo+'","iname":"'+iname+'","ichassis":"'+ichassis+'","iengin":"'+iengin+'","isale_amount":"'+isale_amount+'","ihypo":"'+iihypo+'","is_name":"'+str(name_found)+'","is_chassis":"'+str(chassis_found)+'","is_engin":"'+str(engin_found)+'","is_sale_amount":"'+str(sale_amount_found)+'","is_hypo":"'+str(hypo_found)+'","last_name":"'+str(name2)+'","year_of_manuf":"'+str(YOMfg)+'","ins_date":"'+str(ins_date)+'"}'
print(json_data)