#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <getopt.h>
#include <iconv.h>
#include <time.h>

#include "ts.h"
#include "sdt.h"
#include "eit.h"
#include "ts_ctl.h"

typedef		struct	_ContentTYPE{
	char	*japanese ;
	char	*english ;
}CONTENT_TYPE;

#define		CAT_COUNT		16
static  CONTENT_TYPE	ContentCatList[CAT_COUNT] = {
	{ "ニュース・報道", "news" },
	{ "スポーツ", "sports" },
	{ "情報", "information" },
	{ "ドラマ", "drama" },
	{ "音楽", "music" },
	{ "バラエティ", "variety" },
	{ "映画", "cinema" },
	{ "アニメ・特撮", "anime" },
	{ "ドキュメンタリー・教養", "documentary" },
	{ "演劇", "stage" },
	{ "趣味・実用", "hobby" },
	{ "福祉", "etc" },			//福祉
	{ "予備", "etc" }, //予備
	{ "予備", "etc" }, //予備
	{ "予備", "etc" }, //予備
	{ "その他", "etc" } //その他
};

SVT_CONTROL	*svttop = NULL;
#define		SECCOUNT	4
char	title[1024];
char	subtitle[1024];
char	desc[102400] = {0};
char	Category[1024];
char	ServiceName[1024];
iconv_t	cd ;

void	xmlspecialchars(char *str)
{
	strrep(str, "&", "&amp;");
	strrep(str, "'", "&apos;");
	strrep(str, "\"", "&quot;");
	strrep(str, "<", "&lt;");
	strrep(str, ">", "&gt;");
}



void	GetSDT(FILE *infile, SVT_CONTROL *svttop, SECcache *secs, int count)
{
	SECcache  *bsecs;

	while((bsecs = readTS(infile, secs, count)) != NULL) {
		/* SDT */
		if((bsecs->pid & 0xFF) == 0x11) {
			dumpSDT(bsecs->buf, svttop);
		}
	}
}
void	GetSDT_chout(FILE *infile, SVT_CONTROL *svttop, SECcache *secs, int count,STATION *station, int * station_count,char *header)
{
	SECcache  *bsecs;

	while((bsecs = readTS(infile, secs, count)) != NULL) {
		/* SDT */
		if((bsecs->pid & 0xFF) == 0x11) {
			dumpSDT_chout(bsecs->buf,svttop,station,station_count,header);
		}
	}
}
void	GetEIT(FILE *infile, FILE *outfile, STATION *psta, SECcache *secs, int count)
{
	SECcache  *bsecs;
	EIT_CONTROL	*eitcur ;
	EIT_CONTROL	*eitnext ;
	EIT_CONTROL	*eittop = NULL;
	char	*outptr ;
	char	*inptr ;
	size_t	ilen;
	size_t	olen;
	time_t	l_time ;
	time_t	end_time ;
	struct	tm	tl ;
	struct	tm	*endtl ;
	char	cendtime[32];
	char	cstarttime[32];

	eittop = calloc(1, sizeof(EIT_CONTROL));
	eitcur = eittop ;
	fseek(infile, 0, SEEK_SET);
	while((bsecs = readTS(infile, secs, SECCOUNT)) != NULL) {
		/* EIT */
		if((bsecs->pid & 0xFF) == 0x12) {
			dumpEIT(bsecs->buf, psta->svId, psta->onId, psta->tsId, eittop);
		}else if((bsecs->pid & 0xFF) == 0x26) {
			dumpEIT(bsecs->buf, psta->svId, psta->onId, psta->tsId, eittop);
		}else if((bsecs->pid & 0xFF) == 0x27) {
			dumpEIT(bsecs->buf, psta->svId, psta->onId, psta->tsId, eittop);
		}
	}
	eitcur = eittop ;
	while(eitcur != NULL){
		if(!eitcur->servid){
			eitcur = eitcur->next ;
			continue ;
		}
		if(eitcur->content_type > CAT_COUNT){
			eitcur->content_type = CAT_COUNT -1 ;
		}
		outptr = title ;
		memset(title, '\0', sizeof(title));
		ilen = strlen(eitcur->title);
		olen = sizeof(title);
		inptr = eitcur->title;
		iconv(cd, &inptr, &ilen, &outptr, &olen);
		xmlspecialchars(title);

		memset(subtitle, '\0', sizeof(subtitle));
		ilen = strlen(eitcur->subtitle);
		olen = sizeof(subtitle);
		outptr = subtitle ;
		inptr = eitcur->subtitle;
		iconv(cd, &inptr, &ilen, &outptr, &olen);
		xmlspecialchars(subtitle);

		memset(desc, '\0', sizeof(desc));
		if ( eitcur->desc ) {
			ilen = strlen(eitcur->desc);
			olen = sizeof(desc);
			outptr = desc ;
			inptr = eitcur->desc;
			iconv(cd, &inptr, &ilen, &outptr, &olen);
			xmlspecialchars(desc);
		}

		memset(Category, '\0', sizeof(Category));
		ilen = strlen(ContentCatList[eitcur->content_type].japanese);
		olen = sizeof(Category);
		outptr = Category ;
		inptr = ContentCatList[eitcur->content_type].japanese;
		iconv(cd, &inptr, &ilen, &outptr, &olen);
		xmlspecialchars(Category);

		tl.tm_sec = eitcur->ss ;
		tl.tm_min = eitcur->hm ;
		tl.tm_hour = eitcur->hh ;
		tl.tm_mday = eitcur->dd ;
		tl.tm_mon = (eitcur->mm - 1);
		tl.tm_year = (eitcur->yy - 1900);
		tl.tm_wday = 0;
		tl.tm_isdst = 0;
		tl.tm_yday = 0;
		l_time = mktime(&tl);
		if((eitcur->ehh == 0) && (eitcur->emm == 0) && (eitcur->ess == 0)){
			(void)time(&l_time);
			end_time = l_time + (60 * 5);		// ５分後に設定
		endtl = localtime(&end_time);
		}else{
			end_time = l_time + eitcur->ehh * 3600 + eitcur->emm * 60 + eitcur->ess;
			endtl = localtime(&end_time);
		}
		memset(cendtime, '\0', sizeof(cendtime));
		memset(cstarttime, '\0', sizeof(cstarttime));
		strftime(cendtime, (sizeof(cendtime) - 1), "%Y%m%d%H%M%S", endtl);
		strftime(cstarttime, (sizeof(cstarttime) - 1), "%Y%m%d%H%M%S", &tl);
#if 1
		fprintf(outfile, "  <programme start=\"%s +0900\" stop=\"%s +0900\" channel=\"%s\">\n",	
				cstarttime, cendtime, psta->ontv);
		fprintf(outfile, "    <title lang=\"ja_JP\">%s</title>\n", title);
		fprintf(outfile, "    <desc lang=\"ja_JP\">%s</desc>\n", subtitle);
		fprintf(outfile, "    <longdesc lang=\"ja_JP\">%s</longdesc>\n", desc);
		fprintf(outfile, "    <category lang=\"ja_JP\">%s</category>\n", Category);
//		fprintf(outfile, "    <category lang=\"en\">%s</category>\n", ContentCatList[eitcur->content_type].english);
		fprintf(outfile, "  </programme>\n");
#else
		fprintf(outfile, "(%x:%x:%x)%s,%s,%s,%s,%s,%s\n",
					eitcur->servid, eitcur->table_id, eitcur->event_id,
					cstarttime, cendtime,
					title, subtitle,
					Category,
					ContentCatList[eitcur->content_type].english);
#endif
#if 0
		fprintf(outfile, "(%x:%x)%04d/%02d/%02d,%02d:%02d:%02d,%02d:%02d:%02d,%s,%s,%s,%s\n",
					eitcur->table_id, eitcur->event_id,
					eitcur->yy, eitcur->mm, eitcur->dd,
					eitcur->hh, eitcur->hm, eitcur->ss,
					eitcur->ehh, eitcur->emm, eitcur->ess,
					eitcur->title, eitcur->subtitle,
					ContentCatList[eitcur->content_type].japanese,
					ContentCatList[eitcur->content_type].english);
#endif
		eitnext = eitcur->next ;
		free(eitcur->title);
		free(eitcur->subtitle);
		free(eitcur);
		eitcur = eitnext ;
	}
	free(eittop);
	eittop = NULL;
}
void checkSta_BS(STATION **station,int *stalength){
	STATION *statmp;
	int chl[90];
	int chlt=0;
	int stal=0;
	STATION * statin= *station;
	statmp=malloc(sizeof(STATION)*2);
	for (int i=0;i<*stalength;i++){
		int noidinchl=1;
		for (int j=0;j<chlt;j++){
			if (chl[j]==statin[i].svId || statin[i].svId >= 290){
				noidinchl=0;
			}
		}
		if (noidinchl==1){
			statmp=realloc(statmp,(stal+1)*sizeof(STATION));
			statmp[stal]=statin[i];
			//memcpy(statmp[stal-1],station[i],sizeof(STATION));
			chl[chlt]=statin[i].svId;
			chlt++;
			stal++;
		}
	}
	//*station=realloc(station,(stal+1)*sizeof(STATION));
	//memcpy(*station,statmp,(stal+1)*sizeof(STATION));
	*station=statmp;
	*stalength=stal;
	//memcpy(statin,statmp,chlt*sizeof(STATION));
	//free(statmp);
	return;
}

void checkSta(STATION **station,int *stalength){
	STATION *statmp;
	int chl[90];
	int chlt=0;
	int stal=0;
	STATION * statin= *station;
	statmp=malloc(sizeof(STATION)*2);
	for (int i=0;i<*stalength;i++){
		int noidinchl=1;
		for (int j=0;j<chlt;j++){
			if (chl[j]==statin[i].svId){
				noidinchl=0;
			}
		}
		if (noidinchl==1){
			statmp=realloc(statmp,(stal+1)*sizeof(STATION));
			statmp[stal]=statin[i];
			//memcpy(statmp[stal-1],station[i],sizeof(STATION));
			chl[chlt]=statin[i].svId;
			chlt++;
			stal++;
		}	
	}
	sleep(1);
	*station=statmp;
	*stalength=stal;//ここいらが怪しい
	//memcpy(statin,statmp,chlt*sizeof(STATION));
	//free(statmp);
	return;
}
int main(int argc, char *argv[])
{

	FILE *infile = stdin;
	FILE *outfile = stdout;
	int		arg_maxcount = 1 ;
	char	*arg_onTV ;
	int   mode = 1;
	int		staCount ;
	int   eitcnt;
	char *file;
	int   inclose = 0;
	int   outclose = 0;
	int		flag = 0 ;
	int	outputhtml = 1;
	SVT_CONTROL	*svtcur ;
	SVT_CONTROL	*svtsave ;
	char	*outptr ;
	char	*inptr ;
	size_t	ilen;
	size_t	olen;
	SECcache   secs[SECCOUNT];
	int rtn;
	int		lp ;
	STATION	*pStas ;
	int		act ;

	/* 興味のあるpidを指定 */
	memset(secs, 0,  sizeof(SECcache) * SECCOUNT);
	secs[0].pid = 0x11;
	secs[1].pid = 0x12;
	secs[2].pid = 0x26;
	secs[3].pid = 0x27;

	if(argc == 4){
		arg_onTV = argv[1];
		file = argv[2];
		if(strcmp(file, "-")) {
			infile = fopen(file, "r");
			inclose = 1;
		}
		if(strcmp(argv[3], "-")) {
			outfile = fopen(argv[3], "w+");
			outclose = 1;
		}
	}else{
		fprintf(stdout, "Usage : %s /BS <tsFile> <outfile>\n", argv[0]);
		fprintf(stdout, "Usage : %s <ontvcode> <tsFile> <outfile>\n", argv[0]);
		fprintf(stdout, "ontvcode チャンネル識別子。****.ontvjapan.com など\n");
		fprintf(stdout, "/BS      BSモード。一つのTSからBS全局のデータを読み込みます。\n");
		fprintf(stdout, "/CS      CSモード。一つのTSから複数局のデータを読み込みます。\n");
		return 0;
	}

	if(strcmp(arg_onTV, "/BS") == 0){
		STATION *sta=malloc(sizeof(STATION)*2);
		int sta_count = 0;
		svttop = calloc(1, sizeof(SVT_CONTROL));
		char *head="BS";
		GetSDT_chout(infile, svttop, secs, SECCOUNT,&sta, &sta_count,head);
		checkSta_BS(&sta,&sta_count);
		//if (sta_count) 
		//printf("Station count: %d\n1st ontv=%s,name=%s\n",sta_count, sta[0].ontv, sta[0].name);
		pStas = sta;
		staCount = sta_count;// sizeof(pStas) / sizeof (STATION);
		act = 0 ;
		outputhtml=1;
	}else if(strcmp(arg_onTV, "/CS") == 0){
		STATION *sta=NULL;
		int sta_count = 0;
		svttop = calloc(1, sizeof(SVT_CONTROL));
		char *head="CS";
		GetSDT_chout(infile, svttop, secs, SECCOUNT,&sta, &sta_count,head);
		checkSta(&sta,&sta_count);
		//if (sta_count) 
		//printf("Station count: %d\n1st ontv=%s,name=%s\n",sta_count, sta[0].ontv, sta[0].name);
		pStas = sta;
		staCount = sta_count;
		//staCount=sizeof(pStas) / sizeof (STATION);
		act = 0 ;
		outputhtml=1;
	}else if(strcmp(arg_onTV, "/TEST") == 0){
		STATION *sta=NULL;
		int sta_count = 0;
		svttop = calloc(1, sizeof(SVT_CONTROL));
		char *head="TEST";
		GetSDT_chout(infile, svttop, secs, SECCOUNT,&sta, &sta_count,head);
		checkSta(&sta,&sta_count);
		//if (sta_count) 
		//printf("Station count: %d\n1st ontv=%s,name=%s\n",sta_count, sta[0].ontv, sta[0].name);
		pStas = sta;
		staCount = sta_count;// sizeof(pStas) / sizeof (STATION);
		act = 0 ;
		outputhtml=1;
	}else{
		/*act = 1 ;
		svttop = calloc(1, sizeof(SVT_CONTROL));
		GetSDT(infile, svttop, secs, SECCOUNT);
		svtcur = svttop->next ;	//先頭
		if(svtcur == NULL){
			free(svttop);
			return ;
		}

		pStas = calloc(1, sizeof(STATION));
		pStas->tsId = svtcur->transport_stream_id ;
		pStas->onId = svtcur->original_network_id ;
		pStas->svId = svtcur->event_id ;
		pStas->ontv = arg_onTV ;
		pStas->name = svtcur->servicename ;
		staCount = 1;*/
		///変更後
		STATION *sta=NULL;
		int sta_count = 0;
		svttop = calloc(1, sizeof(SVT_CONTROL));
		//char *head=arg_onTV;
		GetSDT_chout(infile, svttop, secs, SECCOUNT,&sta, &sta_count,arg_onTV);
		checkSta(&sta,&sta_count);
		//if (sta_count) 
		//printf("Station count: %d\n1st ontv=%s,name=%s\n",sta_count, sta[0].ontv, sta[0].name);
		pStas = sta;
		staCount = sta_count;// sizeof(pStas) / sizeof (STATION);
		act = 0 ;
		outputhtml=1;
	}
	if (outputhtml == 1){
		fprintf(outfile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
		fprintf(outfile, "<!DOCTYPE tv SYSTEM \"xmltv.dtd\">\n\n");
		fprintf(outfile, "<tv generator-info-name=\"tsEPG2xml\" generator-info-url=\"http://localhost/\">\n");

		cd = iconv_open("UTF-8", "EUC-JP");
		for(lp = 0 ; lp < staCount ; lp++){
			memset(ServiceName, '\0', sizeof(ServiceName));
			ilen = strlen(pStas[lp].name);
			olen = sizeof(ServiceName);
			outptr = ServiceName ;
			inptr = pStas[lp].name ;
			iconv(cd, &inptr, &ilen, &outptr, &olen);
			xmlspecialchars(ServiceName);

			fprintf(outfile, "  <channel id=\"%s\">\n", pStas[lp].ontv);
			fprintf(outfile, "    <display-name lang=\"ja_JP\">%s</display-name>\n", ServiceName);
			fprintf(outfile, "  </channel>\n");
		}
		for(lp = 0 ; lp < staCount ; lp++){
			GetEIT(infile, outfile, &pStas[lp], secs, SECCOUNT);
		}
		fprintf(outfile, "</tv>\n");
		if(inclose) {
			fclose(infile);
		}

		if(outclose) {
			fclose(outfile);
		}
		iconv_close(cd);
		if(act){
			free(pStas);
			svtcur = svttop ;	//先頭
			while(svtcur != NULL){
				svtsave = svtcur->next ;
				free(svtcur);
				svtcur = svtsave ;
			}
		}
	}else{
		
	}
	return 0;
}
