# vim: set et ts=4 sw=4 fdm=marker
"""
MIT License

Copyright (c) 2016 Jesse Hogan

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
# TODO Add Tests
from entities import *
import MySQLdb
from pdb import set_trace; B=set_trace
from configfile import configfile

class dbentities(entities):
    def save(self):
        for e in self:
            e.save()

class dbentity(entity):
    # TODO Add Tests

    def __init__(self, id=None):
        # TODO Complete
        self.isnew = True
        self._id = None
            
    @property
    def id(self):
        return self._id

    def save(self):
        if self.isnew:
            self._insert()
        elif self.isdirty:
            self._update()

class connections(entities):

    _instance = None
    def __init__(self):
        super().__init__()
        cfg = configfile.getinstance()
        accts = cfg.accounts.mysqlaccounts
        for acct in accts:
            self += connection(acct)

    @classmethod
    def getinstance(cls):
        if cls._instance == None:
            cls._instance = connections()
        return cls._instance

    @property
    def default(self):
        return self.first

class connection(entity):
    def __init__(self, acct):
        self._account = acct
        self._conn = None

    @property
    def account(self):
        return self._account

    @property
    def _connection(self):
        if not self._conn:
            acct = self.account
            self._conn = MySQLdb.connect(acct.host, acct.username, 
                                         acct.password, acct.database, 
                                         port=acct.port)
        return self._conn                

    def _reconnect(self):
        self._conn = None # force a reconnect
        self._connection

    def query(self, sql, args):
        for _ in range(2):
            try:
                conn = self._connection
                cur = conn.cursor()
                cur.execute(sql, args)
                conn.commit()
                return dbresultset(cur)
            except MySQLdb.OperationalError as ex:
                # TODO[CAR-52] BUG This exception catches more than just connection
                # errors.  It can also catch errors like:
                # _mysql_exceptions.OperationalError: (1136, "Column count
                # doesn't match value count at row 1")
                #
                # TODO Add proper logging
                print('Reconnect')
                self._reconnect()

class dbresultset(entities):
    def __init__(self, cur):
        self._cur = cur

    def __iter__(self):
        for r in self._cur:
            yield dbresult(r)

class dbresult(entity):
    def __init__(self, row):
        self._row = row

    def __iter__(self):
        for f in self._row:
            yield f
    

@@ -1561,32 +1561,61 @@
 def save(self):%0A
+        if self.isvalid:%0A    
         if self.
@@ -1629,24 +1629,28 @@
             
+    
 self._insert
@@ -1660,16 +1660,20 @@
         
+   
+ 
 elif sel
@@ -1691,24 +1691,28 @@
             
+    
 self._update
@@ -1713,16 +1713,88 @@
 update()
+%0A        else:%0A            raise Exception('Won%5C't save invalid object')
 %0A%0Aclass 

Test validity before save()