#include <stdio.h>
#include "sqlite3.h"
#include "kk_log.h"
#include "kk_hal.h"
#include "kk_scene_pollution_check.h"
#include "kk_property_db.h"
kk_pmGrade_t g_pm25GradeMap[] = 
{
	{
		{
			{0,35,10},{36,75,1},{76,150,2},{151,250,3},{251,999,4}
		}
	},	
};
kk_pollution_t  g_pollutionMap[] = 
{
	{
		"CO2",
		{
			{0,1500,1},{1501,2500,2},{2501,3500,3},{3501,9999,4}
		}
	},
	{
		"PM2.5",
		{
			{0,75,1},{76,150,2},{151,250,3},{251,999,4}
		}
	},
	{
		"HCHO",
		{
			{0,40,1},{41,80,2},{81,150,3},{151,999,4}
		}
	},	
	{
		"TVOC",
		{
			{0,40,1},{41,80,2},{81,150,3},{151,999,4}
		}
	},
};
int kk_pollution_level_check(kk_pollution_level_t levelMap[],int val,int num)
{
	int i = 0;
	for(i = 0; i < num; i++){
		if(val > levelMap[i].min && val <= levelMap[i].max){
			return levelMap[i].level;
		}
	}
	return -1;
}
int kk_pollution_check(cJSON *param,int grade)
{
	int i = 0;
	int num = 0;
	int ret = 0;
	cJSON *item = NULL;
	if(param == NULL){
		return -1;
	}
	num = sizeof(g_pollutionMap)/sizeof(kk_pollution_t);
	for(i = 0; i < num; i++){
		item = cJSON_GetObjectItem(param,g_pollutionMap[i].identifier);
		if(item == NULL){
			continue;
		}
		if(item->type != cJSON_Number){
			continue;
		}
		ret = kk_pollution_level_check(g_pollutionMap[i].levelMap,item->valueint,4);
		if(ret != -1){
			if(grade == 1){
				if(ret == 1){
					continue;
				}else{
					return 0;
				}
			}else{
				if(grade == ret){
					return 1;
				}
			}	
		}
	}
	if(grade == 1 && ret == 1){
		return 1;
	}
	return 0;
}

int kk_pollution_condition_check(char *deviceCode,int grade)
{
    int num = 0;
    int i = 0;
    int ret = 0;
    char currentValue[64] = {0};
    num = sizeof(g_pollutionMap)/sizeof(kk_pollution_t);
    for(i = 0; i < num; i++){
        memset(currentValue,0x0,sizeof(currentValue));
        kk_property_db_get_value_directly(deviceCode,g_pollutionMap[i].identifier,currentValue);
        if(strcmp(currentValue,"") == 0){
            continue;
        }
		ret = kk_pollution_level_check(g_pollutionMap[i].levelMap,atoi(currentValue),4);
		if(ret != -1){
			if(grade == 1){
				if(ret == 1){
					continue;
				}else{
					return 0;
				}
			}else{
				if(grade == ret){
					return 1;
				}
			}	
		}        
    }
	if(grade == 1 && ret == 1){
		return 1;
	}
	return 0;
}

int kk_pm25_condition_check(char *deviceCode)
{
    int num = 0;
    int i = 0;
    int ret = 0;
    char currentValue[64] = {0};
    kk_property_db_get_value_directly(deviceCode,"PM2.5",currentValue);
    if(strcmp(currentValue,"") == 0){
        return 0;
    }
    return kk_pollution_level_check(g_pm25GradeMap[i].levelMap,atoi(currentValue),5);
}