import json
import traceback

from db import Database
from datetime import datetime
from config import PaymentStatusDict, AccountTypeDict, OwnershipDict
from log_config.logger import print_log


def get_state_code_equifax(code_number, vendor):
    try:
        with Database() as db:
            db.execute('select code from state where code_number = %s', (code_number,))
            result = db.fetchall()
            print_log(result, vendor)
        return result[0][0]

    except Exception as ex:
        traceback.print_exc()
        raise ex


def get_state_code_number_experian(state):
    try:
        with Database() as db:
            db.execute("select code_number from state where name like '%{}%'".format(state,))
            result = db.fetchall()
        return result[0][0]

    except Exception as ex:
        traceback.print_exc()
        raise ex

def add_pan_details(created_at, pan_validation):
    try:
        with Database() as db:
            db.execute('insert into credit_report (created_at, pan_validation) values (%s, %s)', (created_at, pan_validation))
            result = db.fetchall()
        return True
    except Exception as ex:
        traceback.print_exc()
        raise ex


def jwt_get_user(user_id):
    try:
        with Database() as db:
            db.execute('select * from users where id = %s limit 1', (user_id,))
            result = db.fetchall()
        if result:
            return True
        else:
            return False
    except Exception as ex:
        traceback.print_exc()
        raise ex


def check_foir(app_id, applicant_type, pre_eligibility=False):
    try:
        if pre_eligibility:
            query = 'select * from pre_eligibility_foir where application_id = %s and applicant_type = %s limit 1'
        else:
            query = 'select * from foir where application_id = %s and applicant_type = %s limit 1'
        with Database() as db:
            db.execute(query, (app_id, applicant_type))
            result = db.fetchall()
        if result:
            if len(result) == 1 and result[0][3] == 'Credit Fair EMI':
                return False
            return True
        else:
            return False
    except Exception as ex:
        traceback.print_exc()
        raise ex


def check_credit_report(app_id, applicant_type, pre_eligibility=False):
    try:
        if pre_eligibility:
            query = 'select * from pre_eligibility_credit_report where application_id = %s and applicant_type = %s limit 1'
        else:
            query = 'select * from credit_report where application_id = %s and applicant_type = %s limit 1'
        with Database() as db:
            db.execute(query, (app_id, applicant_type))
            result = db.fetchall()
        if result:
            return True
        else:
            return False
    except Exception as ex:
        traceback.print_exc()
        raise ex


def save_experian_bureau_data(pull_type, data, application_id, applicant_type, timestamp, panData, vendor=None, pre_eligibility=False):
    try:
        print_log('Entered Database saving stage', vendor)
        responseHeader = data['Body']['ProcessResponse']['Out'] if 'Body' in data else data
        activeCreditCardLimit = 0
        sanctionAmount = 0
        VoterIDList = []
        contactInfoList = []
        PANIdsList = []
        AddressInfoList = []
        NationalIdsList = []
        NoOfActiveAccounts = 0
        TotalPastDue = 0
        Score = 0
        Past12Months = 0
        Past24Months = 0
        TotalEnquiry = 0
        DateOfBirth = None
        zeroBalanceAccount = 0
        pastDueAccount = 0
        foir = []

        if "INProfileResponse" in responseHeader:
            # responseHeader = xmltodict.parse(responseHeader)
            ReportData = responseHeader["INProfileResponse"]
            if "UserMessage" in ReportData and ReportData["UserMessage"]["UserMessageText"] is not None and \
                    ReportData["UserMessage"]["UserMessageText"] != 'Normal Response':
                ErrorMessage = ReportData["UserMessage"]["UserMessageText"]
            if "Header" in ReportData and ReportData["Header"]["MessageText"] is not None:
                ErrorMessage = ReportData["Header"]["MessageText"]

            Score = ReportData["SCORE"]["BureauScore"]

            if "CAIS_Account" in ReportData:
                AccountData = ReportData["CAIS_Account"]
                if "CAIS_Summary" in AccountData:
                    AccountSummary = AccountData["CAIS_Summary"]
                    totalEnquiry = int(ReportData["TotalCAPS_Summary"]["TotalCAPSLast180Days"]) + \
                                   int(ReportData["NonCreditCAPS"]["NonCreditCAPS_Summary"]["NonCreditCAPSLast180Days"])

                    NoOfActiveAccounts = AccountSummary["Credit_Account"]["CreditAccountActive"]
                    TotalPastDue = 0
                    Past12Months = totalEnquiry
                    Past24Months = totalEnquiry
                    TotalEnquiry = totalEnquiry
                    zeroBalanceAccount = AccountSummary["Credit_Account"]["CreditAccountClosed"]

                if "CAIS_Account_DETAILS" in AccountData:
                    AccountDetailsSummaryList = AccountData["CAIS_Account_DETAILS"]
                    if AccountDetailsSummaryList:
                        if not isinstance(AccountDetailsSummaryList, list):
                            AccountDetailsSummaryList = [AccountDetailsSummaryList]
                        for foirBucket in AccountDetailsSummaryList:
                            ApprovedAmount = foirBucket["Highest_Credit_or_Original_Loan_Amount"]
                            Balance = foirBucket["Current_Balance"]
                            CreditId = 1
                            # CC_loan = 1  # look into it: 0 when credit loan
                            DPD = get_dpd(foirBucket["CAIS_Account_History"])  # looking into
                            # DateOfBirth = foirBucket["CAIS_Holder_Details"]["Date_of_birth"]
                            if 'CurrentApplication' in ReportData:
                                DateOfBirth = ReportData['CurrentApplication']['Current_Application_Details'][
                                                        'Current_Applicant_Details'][0]['Date_Of_Birth_Applicant']
                            else:
                                DateOfBirth = ReportData['Current_Application']['Current_Application_Details'][
                                    'Current_Applicant_Details']['Date_Of_Birth_Applicant']
                            DateOpened = foirBucket["Open_Date"]
                            DateClosed = foirBucket["Date_Closed"]
                            InterestRate = 0 if not foirBucket["Rate_of_Interest"] else foirBucket["Rate_of_Interest"]
                            InstallmentAmount = 0 if not foirBucket["Scheduled_Monthly_Payment_Amount"] else foirBucket["Scheduled_Monthly_Payment_Amount"]
                            Institution = foirBucket["Subscriber_Name"]
                            # IsOpened = 1  # looking into: 0 when close date not present
                            LastPaymentDate = foirBucket["Date_of_Last_Payment"]
                            LastPayment = foirBucket["Value_of_Credits_Last_Month"]
                            OwnershipType = foirBucket["AccountHoldertypeCode"]
                            PastDueAmount = foirBucket["Amount_Past_Due"]
                            RepaymentTenure = foirBucket["Repayment_Tenure"]
                            AccountType = AccountTypeDict.get(str(foirBucket["Account_Type"]))  # looking into: map using the dict
                            CC_loan = 0 if AccountType == 'Credit Card' else 1
                            IsOpened = 0 if DateClosed else 1

                            foir.append([application_id, CreditId, AccountType, ApprovedAmount, Balance,
                                        InterestRate, RepaymentTenure, InstallmentAmount, CC_loan, DateOpened,
                                        DateClosed, OwnershipDict[OwnershipType], Institution, IsOpened, LastPayment,
                                        PastDueAmount, applicant_type, DPD, LastPaymentDate, timestamp])

                            sanctionAmount += int(foirBucket["Highest_Credit_or_Original_Loan_Amount"]) if foirBucket["Highest_Credit_or_Original_Loan_Amount"] else 0
                            TotalPastDue += 0 if foirBucket["Amount_Past_Due"] is None else int(foirBucket['Amount_Past_Due'])
                            if TotalPastDue > 0:
                                pastDueAccount += 1

                            if AccountType == 10:
                                activeCreditCardLimit += int(foirBucket["Highest_Credit_or_Original_Loan_Amount"])

            if "CAPS" in ReportData and pull_type == 'hard':
                if 'CAPS_Application_Details' in ReportData['CAPS']:
                    AccountDetails = ReportData["CAPS"]["CAPS_Application_Details"]
                    if AccountDetails:
                        if not isinstance(AccountDetails, list):
                            AccountDetails = [AccountDetails]
                        for AccountInfo in AccountDetails:
                            AccountInfo["CAPS_Applicant_Address_Details"] = {k: v if v is not None else '' for k, v in
                                                                             AccountInfo["CAPS_Applicant_Address_Details"].items()}
                            for AddressInfo in AccountInfo["CAPS_Applicant_Address_Details"]:
                                Postal = AccountInfo['CAPS_Applicant_Address_Details']["PINCode"] if "PINCode" in AddressInfo else ''
                                Address = AccountInfo['CAPS_Applicant_Address_Details']["FlatNoPlotNoHouseNo"] + AccountInfo['CAPS_Applicant_Address_Details']["BldgNoSocietyName"] + \
                                              AccountInfo['CAPS_Applicant_Address_Details']["RoadNoNameAreaLocality"] + AccountInfo['CAPS_Applicant_Address_Details']["Landmark"] + AccountInfo['CAPS_Applicant_Address_Details'][
                                                  "City"] if "FlatNoPlotNoHouseNo" in AddressInfo else ''
                                Type = AccountInfo['CAPS_Applicant_Address_Details']["Type"] if "Type" in AddressInfo else ''
                                State = AccountInfo['CAPS_Applicant_Address_Details']["State"] if "State" in AddressInfo else ''
                                AddressInfoList.append(
                                    {'Postal': Postal, 'Address': Address, 'Type': Type, 'State': State})

                        if "CAPS_Applicant_Details" in AccountInfo:
                            ApplicantDetails = AccountInfo["CAPS_Applicant_Details"]
                            if 'IncomeTaxPan' in ApplicantDetails:
                                PANIdsList.append(ApplicantDetails["IncomeTaxPan"])
                            if 'MobilePhoneNumber' in ApplicantDetails:
                                contactInfoList.append(ApplicantDetails["MobilePhoneNumber"])
                            if 'Voter_s_Identity_Card' in ApplicantDetails:
                                VoterIDList.append(ApplicantDetails["Voter_s_Identity_Card"])
                            if 'Universal_ID_Number' in ApplicantDetails:
                                NationalIdsList.append(ApplicantDetails["Universal_ID_Number"])

        if not check_credit_report(application_id, applicant_type, pre_eligibility):
            print_log('Saving to credit report:', vendor)
            credit_report_list = (application_id, Score, NoOfActiveAccounts, activeCreditCardLimit, sanctionAmount, TotalPastDue, Past12Months, Past24Months, TotalEnquiry, zeroBalanceAccount,
                                  pastDueAccount, applicant_type, json.dumps(VoterIDList), json.dumps(contactInfoList), json.dumps(PANIdsList),
                                  json.dumps(AddressInfoList), json.dumps(NationalIdsList), DateOfBirth, timestamp, json.dumps(panData) if panData else None,
                                  'experian', panData.get('panVendor').lower() if panData.get('panVendor') else None)
            print_log(credit_report_list, vendor)
            if pull_type == 'soft':
                if pre_eligibility:
                    credit_report_query = ('insert into pre_eligibility_credit_report (application_id, Score, NoOfActiveAccounts, activeCreditCardLimit'
                                           ',sanctionAmount, TotalPastDue, Past12Months, Past24Months, TotalEnquiry, zeroBalanceAccount'
                                           ',pastDueAccount, applicant_type, VoterID, contactInfoList, PANIdsList, AddressInfoList,'
                                           'NationalIdsList, DateOfBirth, created_at, panValidation, bureau, bureau_type, panVendor) values (%s, %s, %s, %s, %s,'
                                           '%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, 1, %s)')
                else:
                    credit_report_query = ('insert into credit_report (application_id, Score, NoOfActiveAccounts, activeCreditCardLimit'
                                           ',sanctionAmount, TotalPastDue, Past12Months, Past24Months, TotalEnquiry, zeroBalanceAccount'
                                           ',pastDueAccount, applicant_type, VoterID, contactInfoList, PANIdsList, AddressInfoList,'
                                           'NationalIdsList, DateOfBirth, created_at, panValidation, bureau, bureau_type, panVendor) values (%s, %s, %s, %s, %s,'
                                           '%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, 1, %s)')
                with Database() as db:
                    db.execute(credit_report_query, credit_report_list)
                    credit_id = db.lastrowid
            else:
                if pre_eligibility:
                    credit_report_query = ('insert into pre_eligibility_credit_report (application_id, Score, NoOfActiveAccounts, activeCreditCardLimit'
                                           ',sanctionAmount, TotalPastDue, Past12Months, Past24Months, TotalEnquiry, zeroBalanceAccount'
                                           ',pastDueAccount, applicant_type, VoterID, contactInfoList, PANIdsList, AddressInfoList,'
                                           'NationalIdsList, DateOfBirth, created_at, panValidation, bureau, panVendor) values (%s, %s, %s, %s, %s,'
                                           '%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)')
                else:
                    credit_report_query = ('insert into credit_report (application_id, Score, NoOfActiveAccounts, activeCreditCardLimit'
                                           ',sanctionAmount, TotalPastDue, Past12Months, Past24Months, TotalEnquiry, zeroBalanceAccount'
                                           ',pastDueAccount, applicant_type, VoterID, contactInfoList, PANIdsList, AddressInfoList,'
                                           'NationalIdsList, DateOfBirth, created_at, panValidation, bureau, panVendor) values (%s, %s, %s, %s, %s,'
                                           '%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)')
                with Database() as db:
                    db.execute(credit_report_query, credit_report_list)
                    credit_id = db.lastrowid
            if not check_foir(application_id, applicant_type, pre_eligibility):
                if len(foir) > 0:
                    for elem in foir:
                        elem[1] = credit_id
                    print_log('Saving to FOIR', vendor)
                    print_log(foir, vendor)
                    if pre_eligibility:
                        foir_query = ('insert into pre_eligibility_foir (application_id, credit_id, AccountType, ApprovedAmount,'
                                      'Balance, InterestRate, RepaymentTenure, InstallmentAmount, cc_loan, DateOpened,'
                                      'DateClosed, OwnershipType, Institution, isOpened, LastPayment, PastDueAmount,'
                                      'applicant_type, dpd, LastPaymentDate, created_at) values (%s, %s, %s, %s, %s,'
                                      '%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)')
                    else:
                        foir_query = ('insert into foir (application_id, credit_id, AccountType, ApprovedAmount,'
                                      'Balance, InterestRate, RepaymentTenure, InstallmentAmount, cc_loan, DateOpened,'
                                      'DateClosed, OwnershipType, Institution, isOpened, LastPayment, PastDueAmount,'
                                      'applicant_type, dpd, LastPaymentDate, created_at) values (%s, %s, %s, %s, %s,'
                                      '%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)')
                    with Database() as db:
                        db.executemany(foir_query, foir)
    except Exception as ex:
        print_log(traceback.format_exc(), vendor)
        raise ex


def save_equifax_bureau_data(data, application_id, applicant_type, timestamp, panData, vendor=None):
    try:
        print_log('Equifax bureau database saving entered', vendor)
        responseHeader = data["soapenv:Envelope"]["soapenv:Body"]["sch:InquiryResponse"] if 'soapenv:Envelope' in data else data
        activeCreditCardLimit = 0
        sanctionAmount = 0
        VoterIDList = []
        contactInfoList = []
        PANIdsList = []
        AddressInfoList = []
        NationalIdsList = []
        NoOfActiveAccounts = 0
        TotalPastDue = 0
        Score = 0
        Past12Months = 0
        Past24Months = 0
        TotalEnquiry = 0
        DateOfBirth = None
        zeroBalanceAccount = 0
        pastDueAccount = 0
        foir = []

        if "sch:ReportData" in responseHeader:
            ReportData = responseHeader["sch:ReportData"]
            Score = ReportData["sch:Score"]["sch:Value"]

            if "sch:AccountSummary" in ReportData:
                AccountSummary = ReportData["sch:AccountSummary"]
                NoOfActiveAccounts = AccountSummary["sch:NoOfActiveAccounts"]
                TotalPastDue = AccountSummary["sch:TotalPastDue"]
                EnquirySummary = ReportData["sch:EnquirySummary"]
                Past12Months = EnquirySummary["sch:Past12Months"]
                Past24Months = EnquirySummary["sch:Past24Months"]
                TotalEnquiry = EnquirySummary["sch:Total"]
                zeroBalanceAccount = AccountSummary["sch:NoOfZeroBalanceAccounts"]
                pastDueAccount = AccountSummary["sch:NoOfPastDueAccounts"]
                AccountDetails = ReportData["sch:AccountDetails"]
                if "sch:IDAndContactInfo" in ReportData:
                    IDAndContactInfo = ReportData["sch:IDAndContactInfo"]
                    if "sch:PhoneInfo" in IDAndContactInfo:
                        if "sch:Number" in IDAndContactInfo["sch:PhoneInfo"]:
                            contactInfoList.append(IDAndContactInfo["sch:PhoneInfo"]["sch:Number"])
                        else:
                            for contactInfo in IDAndContactInfo["sch:PhoneInfo"]:
                                contactInfoList.append(contactInfo["sch:Number"])
                    if "sch:PersonalInfo" in IDAndContactInfo:
                        if "sch:DateOfBirth" in IDAndContactInfo["sch:PersonalInfo"]:
                            DateOfBirth = IDAndContactInfo["sch:PersonalInfo"]["sch:DateOfBirth"]

                    if "sch:IdentityInfo" in IDAndContactInfo:
                        if "sch:VoterID" in IDAndContactInfo["sch:IdentityInfo"]:
                            if "sch:IdNumber" in IDAndContactInfo["sch:IdentityInfo"]["sch:VoterID"]:
                                VoterIDList.append(IDAndContactInfo["sch:IdentityInfo"]["sch:VoterID"]["sch:IdNumber"])
                            else:
                                for VoterIDs in IDAndContactInfo["sch:IdentityInfo"]["sch:VoterID"]:
                                    VoterIDList.append(VoterIDs["sch:IdNumber"])
                        if "sch:PANId" in IDAndContactInfo["sch:IdentityInfo"]:
                            if "sch:IdNumber" in IDAndContactInfo["sch:IdentityInfo"]["sch:PANId"]:
                                PANIdsList.append(IDAndContactInfo["sch:IdentityInfo"]["sch:PANId"]["sch:IdNumber"])
                            else:
                                for PANIds in IDAndContactInfo["sch:IdentityInfo"]["sch:PANId"]:
                                    PANIdsList.append(PANIds["sch:IdNumber"])

                        if "sch:NationalIDCard" in IDAndContactInfo["sch:IdentityInfo"]:
                            if "sch:IdNumber" in IDAndContactInfo["sch:IdentityInfo"]["sch:NationalIDCard"]:
                                NationalIdsList.append(
                                    IDAndContactInfo["sch:IdentityInfo"]["sch:NationalIDCard"]["sch:IdNumber"])
                            else:
                                for PANIds in IDAndContactInfo["sch:IdentityInfo"]["sch:NationalIDCard"]:
                                    NationalIdsList.append(PANIds["sch:IdNumber"])

                    if "sch:AddressInfo" in IDAndContactInfo:
                        Postal = ''
                        Address = ''
                        Type = ''
                        State = ''
                        if "@seq" in IDAndContactInfo["sch:AddressInfo"]:
                            if "sch:Postal" in IDAndContactInfo["sch:AddressInfo"]:
                                Postal = IDAndContactInfo["sch:AddressInfo"]["sch:Postal"]
                            if "sch:Address" in IDAndContactInfo["sch:AddressInfo"]:
                                Address = IDAndContactInfo["sch:AddressInfo"]["sch:Address"]
                            if "sch:Type" in IDAndContactInfo["sch:AddressInfo"]:
                                Type = IDAndContactInfo["sch:AddressInfo"]["sch:Type"]
                            if "sch:State" in IDAndContactInfo["sch:AddressInfo"]:
                                State = IDAndContactInfo["sch:AddressInfo"]["sch:State"]
                            AddressInfoList.append(
                                {'Postal': Postal, 'Address': Address, 'Type': Type, 'State': State})
                        else:
                            for AddressInfo in IDAndContactInfo["sch:AddressInfo"]:
                                if "sch:Postal" in AddressInfo:
                                    Postal = AddressInfo["sch:Postal"]
                                if "sch:Address" in AddressInfo:
                                    Address = AddressInfo["sch:Address"]
                                if "sch:Type" in AddressInfo:
                                    Type = AddressInfo["sch:Type"]
                                if "sch:State" in AddressInfo:
                                    State = AddressInfo["sch:State"]
                                AddressInfoList.append(
                                    {'Postal': Postal, 'Address': Address, 'Type': Type, 'State': State})

                if "@seq" in AccountDetails["sch:Account"]:
                    detailsView = get_account_data(AccountDetails["sch:Account"], application_id, applicant_type)
                    activeCreditCardLimit += detailsView[0]
                    sanctionAmount += detailsView[1]
                    foir.append(detailsView[2])
                else:
                    for accounts in AccountDetails["sch:Account"]:
                        detailsView = get_account_data(accounts, application_id, applicant_type)
                        activeCreditCardLimit += detailsView[0]
                        sanctionAmount += detailsView[1]
                        foir.append(detailsView[2])
        print_log('Saving to credit report', vendor)
        credit_report_list = (application_id, Score, NoOfActiveAccounts, activeCreditCardLimit, sanctionAmount,
                              TotalPastDue, Past12Months, Past24Months, TotalEnquiry, zeroBalanceAccount,
                              pastDueAccount, applicant_type, json.dumps(VoterIDList), json.dumps(contactInfoList), json.dumps(PANIdsList),
                              json.dumps(AddressInfoList), json.dumps(NationalIdsList), DateOfBirth, timestamp, json.dumps(panData) if panData else None,
                              'equifax', panData.get('panVendor').lower() if panData.get('panVendor') else None)
        with Database() as db:
            db.execute('insert into credit_report (application_id, Score, NoOfActiveAccounts, activeCreditCardLimit'
                       ',sanctionAmount, TotalPastDue, Past12Months, Past24Months, TotalEnquiry, zeroBalanceAccount'
                       ',pastDueAccount, applicant_type, VoterID, contactInfoList, PANIdsList, AddressInfoList,'
                       'NationalIdsList, DateOfBirth, created_at, panValidation, bureau, panVendor) values (%s, %s, %s, %s, %s,'
                       '%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)', credit_report_list)
            credit_id = db.lastrowid
        if len(foir) > 0:
            print_log('Saving to FOIR', vendor)
            for idx in range(len(foir)):
                foir[idx] = list(foir[idx])
                foir[idx].append(credit_id)

            with Database() as db:
                db.executemany('insert into foir (application_id, AccountType, ApprovedAmount,'
                               'Balance, InterestRate, RepaymentTenure, InstallmentAmount, cc_loan, DateOpened,'
                               'DateClosed, OwnershipType, Institution, isOpened, LastPayment, PastDueAmount,'
                               'applicant_type, dpd, LastPaymentDate, created_at, credit_id) values (%s, %s, %s, %s, %s,'
                               '%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)', foir)

    except Exception as ex:
        traceback.print_exc()
        raise ex


def get_account_data(accounts, application_id, applicant_type):
    try:
        activeCreditCardLimit = 0
        sanctionAmount = 0
        timestamp = datetime.now()
        historyType = []

        try:
            historyType.append(accounts["sch:History48Months"]["sch:Month"]["sch:PaymentStatus"])
        except:
            for history in accounts["sch:History48Months"]["sch:Month"]:
                historyType.append(history["sch:PaymentStatus"])

        if "sch:AccountType" in accounts and accounts[
            "sch:AccountType"] == "Credit Card" and "sch:CreditLimit" in accounts \
                and accounts["sch:Open"] == "Yes":
            activeCreditCardLimit = float(accounts["sch:CreditLimit"])

        if "sch:Open" in accounts and accounts[
            "sch:Open"] == "Yes" and "sch:SanctionAmount" in accounts:
            sanctionAmount = float(accounts["sch:SanctionAmount"])
        elif "sch:Open" in accounts and accounts["sch:Open"] == "Yes" and "sch:AccountType" in accounts and \
                accounts["sch:AccountType"] == "Credit Card":
            if "sch:CreditLimit" in accounts:
                sanctionAmount = float(accounts["sch:CreditLimit"])
            elif "sch:HighCredit" in accounts:
                sanctionAmount = float(accounts["sch:HighCredit"])

        ApprovedAmount = 0
        Balance = 0
        DateOpened = None
        DateClosed = None
        LastPaymentDate = None
        InterestRate = 'NA'
        cc_loan = 0
        dpd = []
        OwnershipType = None
        Institution = None
        isOpened = 0
        LastPayment = 0
        PastDueAmount = 0
        RepaymentTenure = 0
        InstallmentAmount = 0
        if "sch:AccountType" in accounts and accounts["sch:AccountType"] != "Credit Card":
            if "sch:SanctionAmount" in accounts:
                ApprovedAmount = accounts["sch:SanctionAmount"]
                if ApprovedAmount is None:
                    ApprovedAmount = 0
            AccountDetails = get_account_details(accounts)
            cc_loan = 1
            Balance = AccountDetails.get("Balance")
            InterestRate = AccountDetails.get("InterestRate")
            DateOpened = AccountDetails.get("DateOpened")
            DateClosed = AccountDetails.get("DateClosed")
            OwnershipType = AccountDetails.get("OwnershipType")
            Institution = AccountDetails.get("Institution")
            RepaymentTenure = AccountDetails.get("RepaymentTenure")
            InstallmentAmount = AccountDetails.get("InstallmentAmount")
            isOpened = AccountDetails.get("isOpened")
            LastPayment = AccountDetails.get("LastPayment")
            PastDueAmount = AccountDetails.get("PastDueAmount")
            LastPaymentDate = AccountDetails.get("LastPaymentDate")

            dpd = dict((i, historyType.count(i)) for i in historyType)

        elif "sch:AccountType" in accounts and accounts["sch:AccountType"] == "Credit Card":
            if "sch:CreditLimit" in accounts:
                ApprovedAmount = accounts["sch:CreditLimit"]
                if ApprovedAmount == None or ApprovedAmount == 0:
                    ApprovedAmount = accounts["sch:HighCredit"]

            AccountDetails = get_account_details(accounts)
            cc_loan = 0
            Balance = AccountDetails.get("Balance")
            InterestRate = AccountDetails.get("InterestRate")
            DateOpened = AccountDetails.get("DateOpened")
            DateClosed = AccountDetails.get("DateClosed")
            OwnershipType = AccountDetails.get("OwnershipType")
            Institution = AccountDetails.get("Institution")
            RepaymentTenure = AccountDetails.get("RepaymentTenure")
            InstallmentAmount = AccountDetails.get("InstallmentAmount")
            isOpened = AccountDetails.get("isOpened")
            LastPayment = AccountDetails.get("LastPayment")
            PastDueAmount = AccountDetails.get("PastDueAmount")
            LastPaymentDate = AccountDetails.get("LastPaymentDate")

            if InstallmentAmount == None or InstallmentAmount == 0:
                if ApprovedAmount != 0:
                    InstallmentAmount = ApprovedAmount

            dpd = dict((i, historyType.count(i)) for i in historyType)

        foir = (application_id, accounts["sch:AccountType"], float(ApprovedAmount), float(Balance),
                InterestRate,
                int(RepaymentTenure),
                float(InstallmentAmount), int(cc_loan), DateOpened, DateClosed, OwnershipType, Institution,
                isOpened, LastPayment, PastDueAmount, applicant_type, json.dumps(dpd), LastPaymentDate, timestamp)

        return [activeCreditCardLimit, sanctionAmount, foir]
    except Exception as ex:
        traceback.print_exc()
        raise ex


def get_account_details(accounts):
    try:
        date_opened = None
        date_closed = None
        last_payment_date = None
        interest_rate = 'NA'
        ownership_type = None
        institution = None
        repayment_tenure = 0
        last_payment = 0
        installment_amount = 0
        past_due_amount = 0
        is_opened = 0
        balance = 0

        if "sch:Balance" in accounts:
            balance = accounts["sch:Balance"]
            if balance is None:
                balance = 0
        if "sch:InterestRate" in accounts:
            interest_rate = accounts["sch:InterestRate"]
            if interest_rate is None:
                interest_rate = 0
        if "sch:DateOpened" in accounts:
            date_opened = accounts["sch:DateOpened"]
        if date_opened is not None:
            date_opened = date_opened + ' 00:00:00'
        if "sch:OwnershipType" in accounts:
            ownership_type = accounts["sch:OwnershipType"]
        if "sch:DateClosed" in accounts:
            date_closed = accounts["sch:DateClosed"]
        if "sch:Institution" in accounts:
            institution = accounts["sch:Institution"]
        if "sch:PastDueAmount" in accounts:
            past_due_amount = accounts["sch:PastDueAmount"]
        if "sch:LastPayment" in accounts:
            last_payment = accounts["sch:LastPayment"]
        if "sch:LastPaymentDate" in accounts:
            last_payment_date = accounts["sch:LastPaymentDate"]
        if "sch:RepaymentTenure" in accounts:
            repayment_tenure = accounts["sch:RepaymentTenure"]
            if repayment_tenure is None:
                repayment_tenure = 0
        if "sch:InstallmentAmount" in accounts:
            installment_amount = accounts["sch:InstallmentAmount"]
        if "sch:Open" in accounts:
            is_opened = accounts["sch:Open"]
            if is_opened == "Yes":
                is_opened = 1
            elif is_opened == "No":
                is_opened = 0

        return {'Balance': balance, 'InterestRate': interest_rate, 'DateOpened': date_opened,
                'OwnershipType': ownership_type, 'Institution': institution, 'RepaymentTenure': repayment_tenure,
                'InstallmentAmount': installment_amount, 'isOpened': is_opened, 'PastDueAmount': past_due_amount,
                'DateClosed': date_closed, 'LastPayment': last_payment, 'LastPaymentDate': last_payment_date}

    except Exception as ex:
        traceback.print_exc()
        raise ex


def get_dpd(cais_account_history) :
    try:
        zero_bucket = first_bucket = second_bucket = third_bucket = four_bucket = five_bucket = six_bucket = set_bucket = std_bucket = sub_bucket = dbt_bucket = sma_bucket = lss_bucket = 0
        if isinstance(cais_account_history, dict):
            cais_account_history = [cais_account_history]
        for accountHistory in cais_account_history:
            if accountHistory['Days_Past_Due']:
                if len(accountHistory['Days_Past_Due']) > 0:
                    try:
                        dp_due = int(accountHistory['Days_Past_Due'])
                    except ValueError:
                        dp_due = 0
                    dp_due_string = accountHistory['Days_Past_Due']
                    if 1 < dp_due <= 29:
                        zero_bucket += 1
                    elif 30 <= dp_due <= 59:
                        first_bucket += 1
                    elif 60 <= dp_due <= 89:
                        second_bucket += 1
                    elif 90 <= dp_due <= 119:
                        third_bucket += 1
                    elif 120 <= dp_due <= 149:
                        four_bucket += 1
                    elif 150 <= dp_due <= 179:
                        five_bucket += 1
                    elif dp_due >= 180:
                        six_bucket += 1
                    elif dp_due_string == "S":
                        set_bucket += 1
                    elif dp_due_string == "D":
                        dbt_bucket += 1
                    elif dp_due_string == "B":
                        sub_bucket += 1
                    elif dp_due_string == "L":
                        lss_bucket += 1
                    elif dp_due_string == "M":
                        sma_bucket += 1

        d_base = '{'
        d_head = '{'
        d_foot = '}'
        if zero_bucket > 0:
            d_head += '"' + PaymentStatusDict["0"] + '":' + str(zero_bucket) + ','
        if first_bucket > 0:
            d_head += '"' + PaymentStatusDict["1"] + '":' + str(first_bucket) + ','
        if second_bucket > 0:
            d_head += '"' + PaymentStatusDict["2"] + '":' + str(second_bucket) + ','
        if third_bucket > 0:
            d_head += '"' + PaymentStatusDict["3"] + '":' + str(third_bucket) + ','
        if four_bucket > 0:
            d_head += '"' + PaymentStatusDict["4"] + '":' + str(four_bucket) + ','
        if first_bucket > 0:
            d_head += '"' + PaymentStatusDict["5"] + '":' + str(five_bucket) + ','
        if six_bucket > 0:
            d_head += '"' + PaymentStatusDict["6"] + '":' + str(six_bucket) + ','
        if std_bucket > 0:
            d_head += '"' + PaymentStatusDict["S"] + '":' + str(std_bucket) + ','
        if sub_bucket > 0:
            d_head += '"' + PaymentStatusDict["B"] + '":' + str(sub_bucket) + ','
        if dbt_bucket > 0:
            d_head += '"' + PaymentStatusDict["D"] + '":' + str(dbt_bucket) + ','
        if sma_bucket > 0:
            d_head += '"' + PaymentStatusDict["M"] + '":' + str(sma_bucket) + ','
        if lss_bucket > 0:
            d_head += '"' + PaymentStatusDict["L"] + '":' + str(lss_bucket) + ','
        if d_head == d_base:
            d_head = "[]"
            d_foot = ""
        else:
            d_head = d_head.rstrip(",")
        return str(d_head + d_foot)
    except Exception as ex:
        traceback.print_exc()
        raise ex


def validate_basic_auth(key, secret, ip):
    try:
        with Database() as db:
            db.execute('select * from vendor_api_credentials where `key` = %s and secret = %s', key, secret)
            result = db.fetchall()
        ip_list = result[0][4]
        if result and ip in ip_list:
            return True
        return False
    except Exception as ex:
        traceback.print_exc()
        raise ex
