#include <sys/poll.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <assert.h>
#include <time.h>
#include <pthread.h>
#include "hiredis/hiredis.h"
#include "iniparser/iniparser.h"

#define Boolean int
#define TRUE 1
#define FALSE 0
#define MAX_PIPE_BUFSIZE    256

//BARESIP_STATUS
#define IDLE        0
#define INUSE       1
#define RING        2
#define RINGING     3
#define HOLD        4
#define OFFLINE     5
#define DIALING     6
//BARESIP_REG
#define REGISTER_FAIL   0
#define REGISTER_OK     1
//DEV_TYPE
#define SPEAKER     0
#define SPEAKER2    1
#define SPEAKER3    1
#define INTERCOM    2
#define GATEWAYE    3
//LED_STATUS
#define Led_Off     0
#define Led_On      1
#define Led_Fast    2
#define Led_Slow    3
//REDIS_CHANNEL
#define BARESIP_CHAN    0
#define GPIO_CHAN       1
//GPIO_STATUS
#define GPIO_OFF    0
#define GPIO_ON     1
//DIN
#define DOWN    0
#define UP      1

#define SPK_CONF    "/etc/speaker.conf"
#define VOL_CONF    "/oem/etc/volctrl.conf"

//operator log type
#define BTN			"BUTTON"
#define FUN			"FUNCTION"
#define STA         "SIP STATE"

static int BARESIP_STATUS = OFFLINE;
static int keyLedStatus = Led_On;
static int DEBUG = FALSE;
static int ACCOUNT1_REG = REGISTER_FAIL;
static int ACCOUNT2_REG = REGISTER_FAIL;
static int ACCOUNT3_REG = REGISTER_FAIL;
static int ACCOUNTP2P_REG = REGISTER_FAIL;
static int RELAY_STATE = GPIO_OFF;
static int press_down = FALSE;
static int DEV_TYPE = SPEAKER;
static int CURRENT_CALLS = 0;
static int regcount=0;
static char DTMF_STRING[32] = "\0";

/*
*   @cmd 执行命令
*   @value 命令结果指针
*   @lenth 存储结果长度
int GetCmdValue(char *cmd, char *value, int lenth)
{
    bzero(value, lenth);
    FILE *fp = popen(cmd,"r");
    if(fp != NULL){
        fread(value, 1, lenth, fp);
        pclose(fp);
    } else {
        printf("Handle \"%s\" failed.\n", cmd);
        return FALSE;
    }
    return TRUE;
}
*/
int GetCmdValue(char *file, char *key, char *value, int lenth)
{
	dictionary  *   ini ;
	ini = iniparser_load(file);
	
    if (ini==NULL) {
        fprintf(stderr, "cannot parse file: %s\n", file);
        return FALSE ;
    }
	strcpy(value, iniparser_getstring(ini, key, ""));
	if(DEBUG)
		printf("keystr: \"%s\" ; value: %s.\n", key, value);
	iniparser_freedict(ini);
	return TRUE;
}

//控制功放的开启/关闭,TRUE/FALSE
// void amplifier_switch(Boolean enable){
//     if(enable){
//         system("/etc/scripts/pa_mute.sh 0");
//     }
//     else
//     {
//         system("/etc/scripts/pa_mute.sh 1");
//     }
// }

Boolean get_ip(char * pv)
{
        FILE * fp;
        char cmdbuf[128], value[32];
        char *tmp=NULL;
        sprintf(cmdbuf,"/sbin/ifconfig eth1 | grep 'inet ' | awk '{print $2}'");
        fp = popen(cmdbuf, "r");
        if (fp == NULL) {
                // printf("Fail to open pipe\n");
                return FALSE;
        }

        memset(value,0,sizeof(value));

        if (!feof(fp) && fgets(value,32,fp) != NULL)
            ;
            // printf("value:%s\n", value);
        else {
            printf("ip wrong\n");
            return FALSE;
        }

        pclose(fp);

        if(strlen(value) < 10)
            return FALSE;
        if(tmp = strstr(value,"\n"))
        {
            *tmp = '\0';
        }
        strcpy(pv,value);
        return TRUE;
}

void writeLog(char *type,char *action, char *remark)
{
	char logstr[256];
    redisContext *pContext = redisConnect("127.0.0.1", 6379);

    if (NULL == pContext || pContext->err == 1)
    {
        printf("%s\n", pContext->errstr);
        return;
    }
	sprintf(logstr, "%s,%s,%s", type, action, remark);
    redisReply *pReply;
    pReply = redisCommand(pContext, "LPUSH writelog-channel %s", logstr);

    freeReplyObject(pReply);
	redisFree(pContext);
}

int PlayIP()
{
    char language[32];
    GetCmdValue(SPK_CONF, "system:language", language, sizeof(language));

    char ipaddr[16],cmd_line[240];
    // system("/usr/bin/amixer -q sset 'Master',0 29");
    // amplifier_switch(TRUE); //开启功放
    if(!get_ip(ipaddr)) {
        if (strcmp(language, "en") == 0){
            system("mpg123 /usr/share/sounds/en/get_ip_failed.mp3");
        }else{
            system("mpg123 /usr/share/sounds/cn/get_ip_failed.mp3");
        }
        return 0;
    }

    if (strcmp(language, "en") == 0){
        strcpy(cmd_line,"cd /usr/share/sounds/en/;mpg123 ");
    }else{
        strcpy(cmd_line,"cd /usr/share/sounds/cn/;mpg123 ");
    }

    int i;
    for (i=0;i<strlen(ipaddr);i++){
        switch(ipaddr[i])
        {
            case '0':
                strcat(cmd_line,"digit-0.mp3 ");
                break;
            case '1':
                strcat(cmd_line,"digit-1.mp3 ");
                break;
            case '2':
                strcat(cmd_line,"digit-2.mp3 ");
                break;
            case '3':
                strcat(cmd_line,"digit-3.mp3 ");
                break;
            case '4':
                strcat(cmd_line,"digit-4.mp3 ");
                break;
            case '5':
                strcat(cmd_line,"digit-5.mp3 ");
                break;
            case '6':
                strcat(cmd_line,"digit-6.mp3 ");
                break;
            case '7':
                strcat(cmd_line,"digit-7.mp3 ");
                break;
            case '8':
                strcat(cmd_line,"digit-8.mp3 ");
                break;
            case '9':
                strcat(cmd_line,"digit-9.mp3 ");
                break;
            case '.':
                strcat(cmd_line,"dian.mp3 ");
                break;
        }
    }
    system(cmd_line);

    // amplifier_switch(FALSE); //关闭功放
    // system("/etc/scripts/set_volume.sh resume");
    writeLog( FUN, "Play IP Address", ipaddr );
    return 0;
}


int main(int argc, char *argv[]){
    dictionary  *   ini ;
    char alwaysPlayIP[8];

    // sleep(2);
    GetCmdValue(VOL_CONF, "volume:always_play_ip", alwaysPlayIP, sizeof(alwaysPlayIP));
    if (strcmp(alwaysPlayIP, "yes") == 0)
    {
        system("/usr/bin/amixer -q sset 'DAC',0 160");
        PlayIP();
        return TRUE;
    }

    ini = iniparser_load(SPK_CONF);
    
    if (ini==NULL) {
        fprintf(stderr, "cannot parse file: %s\n", SPK_CONF);
        return FALSE ;
    }

    if(strcmp(iniparser_getstring(ini, "account_info_1:enable", "no"),"yes") == 0)
    {
        goto end;
    }
    else if(strcmp(iniparser_getstring(ini, "account_info_2:enable", "no"),"yes") == 0)
    {
        goto end;
    }
    else if(strcmp(iniparser_getstring(ini, "account_info_3:enable", "no"),"yes") == 0)
    {
        goto end;
    }
    else if(strcmp(iniparser_getstring(ini, "account_info_p2p:enable", "no"),"yes") == 0)
    {
        goto end;
    }
    else if(strcmp(iniparser_getstring(ini, "multicast_player:enable", "no"),"yes") == 0)
    {
        goto end;
    }
    else if(strcmp(iniparser_getstring(ini, "onvif:enable", "no"),"yes") == 0)
    {
        goto end;
    }
    system("/usr/bin/amixer -q sset 'DAC',0 160");
    PlayIP();

end:
    iniparser_freedict(ini);
    return TRUE;
}
