# Collection of code snippets by Arne Vajhøj 
# (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
import pymysql

from common import *

class MockDataAccessLayer:
    def get_one_record(self, f1):
        return Data(f1, 'X' + str(f1))
    def get_all_records(self):
        return [ Data(1, 'A'), Data(2, 'BB'), Data(3, 'CCC')]

class DbDataAccessLayer:
    def __init__(self):
        self.con = pymysql.connect(host='localhost',user='root',password='',db='Test')
    def get_one_record(self, f1):
        c = self.con.cursor()
        c.execute('SELECT f2 FROM t1 WHERE f1 = %s', (f1,))
        f2 = c.fetchone()[0]
        c.close()
        return Data(f1, f2)
    def get_all_records(self):
        c = self.con.cursor()
        c.execute('SELECT f1,f2 FROM t1')
        res = []
        for row in c.fetchall():
            res.append(Data(row[0], row[1]))
        c.close()
        return res

class PlainPresenter:
    def start(self):
        pass
    def one(self, o):
        print('%d %s' % (o.f1, o.f2))
    def finish(self):
        pass

class HtmlPresenter:
    def __init__(self):
        self.lbl1 = 'F1'
        self.lbl2 = 'F2'
    def start(self):
        print('<table>')
        print('<tr>')
        print('<th>%s</th>' % (self.lbl1))
        print('<th>%s</th>' % (self.lbl2))
        print('</tr>')
    def one(self, o):
        print('<tr>')
        print('<td>%s</td>' % (o.f1))
        print('<td>%s</td>' % (o.f2))
        print('</tr>')
    def finish(self):
        print('</table>')

class StandardApplication:
    def __init__(self):
        #self.dal = MockDataAccessLayer()
        self.dal = DbDataAccessLayer()
        #self.p = PlainPresenter()
        self.p = HtmlPresenter()
    def run(self):
        self.p.start()
        o = self.dal.get_one_record(2)
        self.p.one(o)
        self.p.finish()
        self.p.start()
        for o1 in  self.dal.get_all_records():
            self.p.one(o1)
        self.p.finish()

app = StandardApplication()
app.run()
