# -*- coding: utf-8 -*-
"""
Eléments communs au projet Camétéo

Created on Fri Aug 18 21:35:59 2017

@author: arofarn
"""

###########
# IMPORTS #
###########

from datetime import datetime, timedelta
from configparser import ConfigParser
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import os, sys

#################
# CONFIGURATION #
#################

script_path = os.path.dirname(sys.argv[0])
script_dir = os.path.abspath(script_path)

parser = ConfigParser()
parser.read(script_dir + '/cameteo.conf')

#Misc
TimeZone = parser['MISC'].get('TimeZone', fallback=0)

#SQL
sql_host = parser['SQL'].get('sql_host', fallback='localhost')
sql_port = parser['SQL'].get('sql_port', fallback=3306)
sql_base = parser['SQL'].get('sql_base', fallback='cameteo')
sql_user = parser['SQL'].get('sql_user', fallback='cameteo')
sql_pass = parser['SQL'].get('sql_pass', fallback='oetemac')
sql_sys  = parser['SQL'].get('sql_sys', fallback='mysql')
sql_api  = parser['SQL'].get('sql_api', fallback='pymysql')
sql_verbose  = bool(int(parser['SQL'].get('sql_verbose', fallback=0)))

sql_uri = sql_sys + '+' + sql_api + '://' + sql_user + ':' + sql_pass + '@' + sql_host + ':' + sql_port + '/' + sql_base

#MQTT
mqtt_host       = parser['MQTT'].get('mqtt_host', fallback='localhost')
mqtt_port       = int(parser['MQTT'].get('mqtt_port', fallback=1883))
mqtt_client_id  = parser['MQTT'].get('mqtt_client_id', fallback='mqtt2sql')
mqtt_user       = parser['MQTT'].get('mqtt_user', fallback='cameteo')
mqtt_pass       = parser['MQTT'].get('mqtt_pass', fallback='oetemac')
mqtt_qos        = parser['MQTT'].get('mqtt_qos', fallback=0)
mqtt_topic      = parser['MQTT'].get('mqtt_topic', fallback='sensors/#')

#####################
# Flask & SQLAchemy #
#####################

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = sql_uri
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['BOOTSTRAP_USE_MINIFIED'] = False
app.config['BOOTSTRAP_SERVE_LOCAL'] = True
#app.config['SQLALCHEMY_POOL_RECYCLE'] = 600

######################
# SQLAlchemy Classes #
######################

db = SQLAlchemy(app)

class SensorModel(db.Model):
    """SensorModel : classe des modèles de capteur"""
    
    __tablename__= 'sensor_model'
    
    name=db.Column(db.String(20), primary_key=True)
    brand=db.Column(db.String(20), nullable=False)
    description=db.Column(db.String(1000))

    def __repr__(self):
        return "<SensorModel(name='%s', brand='%s', description='%s')>" % (self.name, self.brand, self.description)

    def __str__(self):
        return "%s %s" % (self.brand, self.name)

class Sensor(db.Model):
    """Sensor : classe des capteurs"""
    
    __tablename__= 'sensors'
    
    name = db.Column(db.String(20), db.ForeignKey('data.sensor_id'), primary_key=True)
    model_id = db.Column(db.String(20), db.ForeignKey('sensor_model.name'), nullable=False)
    description = db.Column(db.String(1000))
    
    model = db.relationship("SensorModel", backref=db.backref('sensors', lazy=True))
    
    def __repr__(self):
        return "<Sensor(name='%s', model='%s', description='%s')>" % (self.name, self.model, self.description)

    def __str__(self):
        return """%s : 
 - Modèle : \t%s
 - Description: \t%s""" % (self.name, self.model, self.description)

class DataType(db.Model):
    """DataType : classe des types de données"""
    
    __tablename__ = 'data_type'
    
    type_id = db.Column(db.String(4), primary_key=True)
    name = db.Column(db.String(20), nullable=False)
    description = db.Column(db.String(1000))
    
    def __repr__(self):
        return "<DataType(name='%s', ID='%s', description='%s')>" % (self.name, self.type_id, self.description)

    def __str__(self):
        return "%s (%s)" % (self.name, self.unit)

class Data(db.Model):
    """Data : classe des données"""
    
    __tablename__ = 'data'
    
    data_id = db.Column(db.BigInteger, primary_key=True)
    dbdate = db.Column(db.DateTime, nullable=False)
    valdate = db.Column(db.DateTime, nullable=False)
    value = db.Column(db.Float, nullable=True)
    unit = db.Column(db.String(20), nullable=True)
    type_id = db.Column(db.String(4), db.ForeignKey('data_type.type_id'), nullable=True)
    sensor_id = db.Column(db.String(20), db.ForeignKey('sensors.name'), nullable=True)
    
    def __repr__(self):
        return "<Data(value='%0.2f', type='%s', date='%s', sensor ID='%s', id='%s')>" % (self.value, self.type_id, self.valdate.utc, self.sensor_id, self.data_id)

    def __str__(self):
        try:        
            val = "{:8.2f} {:8s}".format(self.value, self.unit)
        except:
            val = "  'NULL'         "
        return "{} : {:4s}= {} (capteur: {:s})".format(self.valdate, self.type_id, val, self.sensor_id)
        
