'''
Database

tables:
customer_data
invoices
kasboek

sequence:
name, date, fnum, opd, total, cont
'''

import sqlite3 as sql
from datetime import date as d


def add_inv(in_db):
    '''
    Get a new invoice as a list and add it as a new line to the database
    table - invoices.
    '''

    try:
        con = sql.connect('kozmi.db')
        cur = con.cursor()

        cur.execute('insert into invoices values(?, ?, ?, ?, ?, ?)', in_db)

        con.commit()
    except sql.Error as e:
        print('Error occured: ' + e.args[0])
    finally:
        con.close()


def get_next_invNum(year):
    '''
    Second index in result of select is fnum. It has to be splitted and checked.
    if current year is not equal to the year in last_fnum, change it and start
    the numbers over. Else, just increment the fnum.
    '''

    try:
        con = sql.connect('kozmi.db')
        cur = con.cursor()

        cur.execute('select * from invoices order by rowid desc limit 1')

        last_line = cur.fetchone()
        last_fnum = last_line[2].split('-')
        inv_year = last_line[1].split('-')[2]

        print(last_line)
        print(last_fnum)
        print(inv_year)

        if year != inv_year:
            return 1
        else:
            return str(int(last_fnum[1]) + 1)

    except sql.Error as e:
        print('Error occured: ' + e.args[0])
    finally:
        con.close()

if __name__ == '__main__':
    # test lines
    # add_inv(['', d.today().__format__('%Y-%m-%d'), '001', 'haarsen', 100, False])
    print(get_next_invNum('2017'))
