# -*- coding: utf-8 -*-
"""
Created on Fri Aug 18 21:35:59 2017

@author: arofarn
"""

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

from datetime import datetime, timedelta
from configparser import ConfigParser
from sqlalchemy import *
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

###########
# CLASSES #
###########
Base = declarative_base()
Session = sessionmaker()

class SensorModel(Base):
    """SensorModel : classe des modèles de capteur"""
    
    __tablename__= 'sensor_model'
    
    name=Column(String(20), primary_key=True)
    brand=Column(String(20))
    description=Column(String(1000))
    
    sensors = relationship("Sensor", back_populates="model")

    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(Base):
    """Sensor : classe des capteurs"""
    
    __tablename__= 'sensors'
    
    name=Column(String(20), ForeignKey('data.sensor_id'), primary_key=True)
    description=Column(String(1000))    
    model_id=Column(String(20), ForeignKey('sensor_model.name'))
    
    model = relationship("SensorModel")
    data = relationship("Data", back_populates="sensor")
    
    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(Base):
    """DataType : classe des types de données"""
    
    __tablename__ = 'data_type'
    
    type_id = Column(String(4), primary_key=True)
    name = Column(String(20))
    description=Column(String(1000))
    
    data = relationship("Data", back_populates="data_type")
    
    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(Base):
    """Data : classe des données"""
    
    __tablename__ = 'data'
    
    data_id = Column(BigInteger, primary_key=True)
    dbdate = Column(DateTime)
    valdate = Column(DateTime)
    value = Column(Float)
    unit = Column(String(20))
    type_id = Column(String(4), ForeignKey('data_type.type_id'))
    sensor_id = Column(String(20))
    
    data_type = relationship("DataType", back_populates="data")
    sensor=relationship('Sensor')
    
    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):
        return "{} : {:4s}= {:8.2f} {:8s} (capteur: {:s})".format(self.valdate, self.type_id, self.value, self.unit, self.sensor_id)
        
#################
# CONFIGURATION #
#################

parser = ConfigParser()
parser.read('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)))

#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/#')