__author__ = 'develru'

import sqlite3
from PySide import QtCore


class BookDatabase(QtCore.QAbstractListModel):
    location = 'buecher.db'

    def __init__(self, parent=None):
        super(BookDatabase, self).__init__(parent)
        self.db = sqlite3.connect(self.location)

        sql = 'CREATE TABLE IF NOT EXISTS books(isbn INTEGER PRIMARY KEY, ' \
              'author TEXT, title TEXT)'
        self.cursor = self.db.cursor()
        self.cursor.execute(sql)
        self.db.commit()

        self.all_rows = self.read_all()

    def rowCount(self, parent=QtCore.QModelIndex):
        return len(self.all_rows)

    def data(self, index, role):
        if role == QtCore.Qt.DisplayRole:
            return self.all_rows[index.row()]

    def delete_book(self, index):
        self.beginRemoveRows(QtCore.QModelIndex(), index.row(), index.row())
        data = index.data(QtCore.Qt.DisplayRole)
        if data is not None:
            isbn = data[0]
            self.cursor.execute('''DELETE FROM books WHERE isbn = ? ''', (isbn, ))
            self.db.commit()
            self.all_rows.remove(tuple(data))
        self.endRemoveRows()

    def add_book(self, data):
        self.beginInsertRows(QtCore.QModelIndex(), 0, 0)
        self.cursor.execute('''INSERT INTO books(isbn, author, title)
              VALUES(?, ?, ?)''', (data[0], data[1], data[2]))
        self.db.commit()
        self.all_rows.append(data)
        self.endInsertRows()

    def update_book(self, index, old_data, new_data):
        isbn = new_data[0]
        self.cursor.execute('''UPDATE books SET author = ? WHERE isbn = ?''',
                            (new_data[1], isbn))
        self.cursor.execute('''UPDATE books SET title = ? WHERE isbn = ?''',
                            (new_data[2], isbn))
        self.db.commit()
        ind = self.all_rows.index(tuple(old_data))
        if ind != -1:
            self.all_rows[ind] = tuple(new_data)
            #self.emit.dataChanged(index, index)
        else:
            print("error")


    def read_all(self):
        self.cursor.execute('''SELECT isbn, author, title FROM books''')
        all_rows = self.cursor.fetchall()
        #for row in allRows:
        #    print(row)

        return all_rows

    def reopen(self):
        self.cursor.close()
        self.db.close()
        self.db = sqlite3.connect(self.location)
        self.cursor = self.db.cursor()