#include <stdio.h>
#include <string.h>
#include <time.h>

#include <inttypes.h>


#include "../../status.h"

int init(void * param)
{
    param = param;

    return 0;
}

typedef struct chod_01_t
{
    uint8_t checksum __attribute__ ((packed));
    uint8_t event __attribute__ ((packed));
    uint8_t bi __attribute__ ((packed));
    uint8_t key __attribute__ ((packed));
    uint8_t status __attribute__ ((packed));
    uint16_t id __attribute__ ((packed));
    uint8_t retranslation __attribute__ ((packed));
    uint8_t separator __attribute__ ((packed));
    uint8_t year __attribute__ ((packed));
    uint8_t month __attribute__ ((packed));
    uint8_t day __attribute__ ((packed));
    uint8_t hour __attribute__ ((packed));
    uint8_t min __attribute__ ((packed));
    uint8_t sec __attribute__ ((packed));
    uint8_t delimiter __attribute__ ((packed));
} chod_01_t;

#define ONOFF		7
#define ALARM		6
#define CC		5
#define ALT_ALARM	4
#define BATT_FAULT	3
#define CONN_LOST	2
#define POWER_FAULT	1
#define GEN_FAULT	0

unsigned int process(unsigned char * data, unsigned int length, unsigned long long int * id, time_t * tm, unsigned int * status, unsigned char * result, unsigned int * pbb_status, unsigned int * data_type)
{
    struct chod_01_t * chod_01;
    struct tm t;
    
    if (length != 16)
    {
	printf("Chod_01: Bad length %d\n", length);
	return 0;
    }
    chod_01 = (struct chod_01_t *)data;
    printf("Chod_01: status 0x%02X\n", chod_01->status);
    chod_01->id -= 0x2020;
    t.tm_year = chod_01->year - 0x30 + 100;
    t.tm_mon = chod_01->month - 0x30 - 1;
    t.tm_mday = chod_01->day - 0x30;
    t.tm_hour = chod_01->hour - 0x30;
    t.tm_min = chod_01->min - 0x30;
    t.tm_sec = chod_01->sec - 0x30;

    printf("Chod_01: %d, on %04d-%02d-%02d %02d:%02d:%02d\n", chod_01->id, t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec);

    *id = chod_01->id;
    *tm = mktime(&t);
    *status= chod_01->status;
    *pbb_status = PBB_OFF;
    *data_type = PBB_NONE;
    if ((chod_01->status & (1 << ONOFF)) || ((chod_01->status & (1 << ALARM)) &&  (chod_01->status & (1 << CC))))
	*pbb_status = PBB_ON;
    if (chod_01->status & 0x0F)
	*pbb_status = PBB_ERROR;
    sprintf(result, "'%d','%d','%d','%d'", chod_01->status, chod_01->bi, chod_01->key, chod_01->event);
    
    return 4;
}
