#include "fb.h"
UINT8 f_pos[4];
UINT8 f_posid;
//#define APP_EV_NEW		0xff01
//static WCHAR fb_new[]={0x65B0,0x5EFA,0};
const EVENT_HANDLER_ENTRY_T fb_state_handlers[] =
{
 //   { EV_DIALOG_DONE,             	            destroyApp },
    { EV_REQUEST_LIST_ITEMS,       	        fbHandleListReq  },
	{ EV_SELECT, 		                      fbSelectItem },
	{ EV_KEY_PRESS,								fbKeypress	},
    { EV_DONE,                     	                  fbBack },	
	{ EV_LIST_NAVIGATE,							fHandleNavigate },
	//{ APP_EV_NEW,                     	                  fbBack },	
	{ STATE_HANDLERS_END,		NULL }
};
UINT32 FbrowserStateEnter( EVENT_STACK_T *ev_st,  void *app,  ENTER_STATE_TYPE_T type )
{
    APP_TXTEDIT_T           *papp = (APP_TXTEDIT_T*)app;
    SU_PORT_T               port = papp->apt.port;
	UINT32					starting_num;
    INT16                  i;
	f_posid=0;
	//ACTIONS_T		action_list;
	dbg("FbrowserStateEnter: ENTER", NULL);
	//SetStringRes( &Resources[RES_NEW_CAPTION], fb_new);
	//action_list.action[0].operation = ACTION_OP_ADD;
	//action_list.action[0].event = APP_EV_NEW;
	//action_list.action[0].action_res = Resources[RES_NEW_CAPTION];
	//action_list.count =2;
	if(type!=ENTER_STATE_ENTER) 
		return RESULT_OK;
		if(papp->setmode==MAIN_MAP)
		{
		f_posid=1;
		u_strcpy(papp->filedir, map_uir);
		}else if (papp->setmode==MAIN_BMAP)
		{
		f_posid=3;
		u_strcpy(papp->filedir, bmap_uir);
		}
		else if(papp->setmode==MAIN_PIC)
		{
		f_posid=2;
		u_strcpy(papp->filedir, pic_uir);
		}
		else if (papp->filedir[0] == 0) 			//判断是否为空
		{
		u_strcpy(papp->filedir, L"/");		
		}		
		//else{
		//u_strcpy(papp->filedir,papp->openfile);	
		//}
        for (i=u_strlen(papp->filedir)-1; i > 0 && papp->filedir[i] != '/' ; i--);	//提取文件夹路径
        papp->filedir[i+1] = 0;
		if(i>0)
		papp->d_true=TRUE;
		


			


    
    FindFile(papp->filedir, L"*",app);

    DRM_SetResource( Resources[RES_LIST_CAPTION], (void*)papp->filedir, (u_strlen(papp->filedir)+1)*sizeof(WCHAR));

    	dialog = UIS_CreateList( &port,
    							 0,
    							 papp->cont,
    							 0,
    							 &starting_num,
    							 0,
    							 2,
								 
    							 0,
    							 Resources[RES_LIST_CAPTION] );
      
    
        if(dialog == 0) return RESULT_FAIL;
    
        papp->apt.dialog = dialog;

        
    	// 昨钺?耧桉铌 玎疣犷蜞? 屐?眢骓?耩噻?镥疱溧螯 starting_num 屐屙蝾?
   	fbSendListItems(ev_st, app, 1, starting_num);
					if(papp->d_true)
					{
					papp->d_true=FALSE;
					//if(f_pos[f_posid]>starting_num)
					//f_pos[f_posid]-=1;
					APP_UtilAddEvUISListChange( ev_st, app, 0, f_pos[f_posid], papp->cont, TRUE, 2, FBF_LEAVE, 0, NULL );
					}

    return RESULT_OK;
}
UINT32 FindFile( WCHAR *folder, WCHAR *filtr ,void *app)
{
    APP_TXTEDIT_T           *papp = (APP_TXTEDIT_T*)app;
	INT32                   err=RESULT_OK;
	FS_SEARCH_PARAMS_T		sp;
	FS_SEARCH_RESULT_T		hResult;
	FS_SEARCH_HANDLE_T		hSearch;

	UINT16		count_files=0, count_res=1;
	UINT32		status = RESULT_OK;
	INT32		i=0, j=0;
	UINT8       mode=0;
	WCHAR       volumes[12];
	WCHAR       search_string[256];
	dbg("FindFile: ENTER", NULL);
    //u_strcpy(folder, L"/c/");	
	if ( folder==NULL || !u_strcmp(folder, L"/")) {
            u_strcpy(search_string, L"/");
    } else {

        if(u_strncmp(folder, L"file:/", 6))
        {
            u_strcpy(search_string, L"file:/");
            u_strcat(search_string, folder);
        } else {
            u_strcpy(search_string, folder);
        }
            
        if (folder[u_strlen(folder)-1] != '/' ) 
            u_strcat(search_string, L"/");
    
        u_strcat(search_string, L"\xFFFE");
        u_strcat(search_string, filtr);
    }
	udbg("FindFile: search_string = '%s'", search_string);

 	
    if (!u_strcmp(search_string, L"/")) {   //是否主盘

        DL_FsVolumeEnum(volumes);  //得到主盘数目

		if (papp->flist)
		{
		free(papp->flist);
		papp->flist = NULL;
		}
		dbg("FindFile: free", NULL);
        papp->flist = suAllocMem(sizeof(FILEINFO)*4, &err);
		dbg("FindFile: suAllocMem", NULL);
        if (err != RESULT_OK) return RESULT_FAIL;

        papp->filedir[0] = '/';

        papp->cont = 0;

        for (i=0; i < 4; i++) {
            papp->flist[i].name[0] = volumes[i*3+1];//'a' + i;
            papp->flist[i].name[1] = 0;
            papp->flist[i].attrib = FS_ATTR_DIRECTORY;

            papp->cont++;
			udbg("papp->flist[i].name=%s",papp->flist[i].name);
            if (volumes[i*3+2] == 0)  break;
        }

        return RESULT_OK;
    }

	
	sp.flags = 0x1C; 
	sp.attrib = 0;
	sp.mask = 0;
	
	status = DL_FsSSearch( sp, search_string, &hSearch, &count_files, 0 );

	if ( status != RESULT_OK ) {
        DL_FsSearchClose( hSearch );
        return RESULT_FAIL;
    }

    dbg("FB: count_files = %d", count_files);
	

	papp->cont = count_files+1;
	if (papp->flist)
	{
	free(papp->flist);
	papp->flist = NULL;
	}
	dbg("FindFile: free", NULL);
    papp->flist = suAllocMem(sizeof(FILEINFO)*(count_files+1), &err);
	dbg("FindFile: suAllocMem", NULL);
    if (err != RESULT_OK) return RESULT_FAIL;
	
	u_strcpy(papp->flist[0].name, L"..");
	papp->flist[0].attrib = FS_ATTR_DIRECTORY;


	for ( i=0, j=1; j<=count_files; i++ ) {

            if (i >= count_files){
                if (mode > 0) {
                    break;
                } else {
                    i=-1;
                    mode=1;
                    continue;
                }
            }

		status = DL_FsSearchResults( hSearch, i, &count_res, &hResult );
		if ( status == RESULT_OK ) 
		{
            if ((mode==0) && !(hResult.attrib&FS_ATTR_DIRECTORY)) continue;
            if ((mode==1) && (hResult.attrib&FS_ATTR_DIRECTORY)) continue;
			udbg("FindFile: hResult.name = '%s'", hResult.name);
            if(!u_strcmp(hResult.name+u_strlen(hResult.name)-1, L"/")) continue;
			if ( hResult.name[0] == '/' )
			u_strcpy(papp->flist[j].name,u_strrchr( hResult.name, '/' ) + 1);
			else
			u_strcpy(papp->flist[j].name,hResult.name);
			//u_strcpy(papp->flist[j].name, u_strrchr(hResult.name, '/')+1);
			papp->flist[j].attrib = hResult.attrib;
			papp->flist[j].ext = u_strrchr(papp->flist[j].name, '.')+1;
			udbg("FindFile: name = '%s'", papp->flist[j].name);
			j++;
		} 
        
	}
	DL_FsSearchClose( hSearch ); 
	
	return RESULT_OK;
}
UINT32 fbSendListItems( EVENT_STACK_T *ev_st,  void *app, UINT32 start, UINT32 num)
{
    APP_TXTEDIT_T           *papp = (APP_TXTEDIT_T*)app;   
	LIST_ENTRY_T			*plist=NULL; 
	UINT32					i, index, status=RESULT_OK;
	UINT32					img_res=0, img_select=0;
	dbg("fbSendListItems: ENTER", NULL);    
    if( num==0 ) return RESULT_FAIL; 
	
	plist = malloc( sizeof(LIST_ENTRY_T)*num ); 
	if( plist==NULL ) return RESULT_FAIL;
	dbg("fbSendListItems: 1", NULL); 

    for( index=0, i=start; (i<start+num) && (i<=papp->cont+1); i++, index++) 
	{

        plist[index].editable = FALSE;			
		plist[index].content.static_entry.can_mark = 1;

        img_select=0;
        img_res=0;


        if (papp->flist[i-1].attrib & FS_ATTR_DIRECTORY) {
            img_res = RES_GIF_FOLDER;
        } else {
			img_res =GetIconByExt(papp->flist[i-1].ext);
		}	

        UIS_MakeContentFromString( "p1q0", &(plist[index].content.static_entry.text), papp->flist[i-1].name, img_res);

	}
	dbg("fbSendListItems: 2", NULL); 


	status = APP_UtilAddEvUISListData( ev_st, app, 0,
									   start, num,
									   FBF_LEAVE,
									   sizeof(LIST_ENTRY_T)*num,
									   plist );
	if( status != RESULT_FAIL )
	{
		status = UIS_HandleEvent(papp->apt.dialog, ev_st);
	}
	dbg("fbSendListItems: ENTER", 3); 
	free(plist);
	dbg("fbSendListItems: END", NULL); 
	return status;
	

}
UINT32 fbSelectItem( EVENT_STACK_T *ev_st,  void *app ) 
{

    UINT32 index =f_pos[f_posid];// AFW_GetEv(ev_st)->data.index;
    APP_TXTEDIT_T           *papp = (APP_TXTEDIT_T*)app; 
	UINT32					status=RESULT_OK;
    //UINT32          i;
	//f_pos=index;
   

    	    if (index == 1 && u_strcmp(papp->filedir, L"/"))
			{
                 dbg("Level Up", NULL);

					FBLevelUp(papp->filedir);
					FindFile(papp->filedir,L"*",app);
	
					UpdateList(ev_st, app, 1);
                    UIS_Refresh();
			}
			
			else
			{
					if (papp->flist[index-1].attrib & FS_ATTR_DIRECTORY)
					{
                        dbg("Open folder", NULL);

   						u_strcat(papp->filedir, papp->flist[index-1].name);
						u_strcat(papp->filedir, L"/");
                        
						FindFile( papp->filedir, L"*",app);

                        UpdateList(ev_st, app, 1);
                        UIS_Refresh();
					}
					else
					{
                        dbg("Open file", NULL);
						//u_strcpy(papp->name,papp->filedir);	
                        //u_strcpy(papp->openfile, L"file:/");
						//cmd_file=FALSE;
						if(papp->setmode==MAIN_MAP||papp->setmode==MAIN_PIC||papp->setmode==MAIN_BMAP)
						{
									
									if(papp->setmode==MAIN_MAP)
									{
									u_strcpy(map_uir, papp->filedir);
			                        u_strcat(map_uir, papp->flist[index-1].name);
									}else if(papp->setmode==MAIN_BMAP)
									{
									u_strcpy(bmap_uir, papp->filedir);
			                        u_strcat(bmap_uir, papp->flist[index-1].name);
									readmap();
									}
									else
									{
									r_pic=TRUE;
									u_strcpy(pic_uir, papp->filedir);
			                        u_strcat(pic_uir, papp->flist[index-1].name);
									readpic();
									}
									papp->setmode=0;
									saveset(app);
									papp->d_true=TRUE;
									status=APP_UtilChangeState( HE_STATE_MAIN, ev_st, app );
						}
						else
						{
						u_strcpy(papp->openfile, papp->filedir);
                        u_strcat(papp->openfile, papp->flist[index-1].name);
						papp->mode=MODE_FB;
                        status=APP_UtilChangeState( HE_STATE_READ, ev_st, app );
						}
					}
			}

	
	return status;
}
UINT32 fbHandleListReq( EVENT_STACK_T *ev_st,  void *app )
{
	APP_TXTEDIT_T			*papp = (APP_TXTEDIT_T*) app;
	EVENT_T					*event;
	UINT32					start, num;

	if( !papp->apt.focused ) return RESULT_OK;

	event = AFW_GetEv( ev_st );

	start = event->data.list_items_req.begin_idx;
	num = event->data.list_items_req.count;

	APP_ConsumeEv( ev_st, app );

    fbSendListItems( ev_st, app, start, num );

    return RESULT_OK;
}
UINT32 fbBack( EVENT_STACK_T *ev_st,  void *app )
{
	APP_TXTEDIT_T			*papp = (APP_TXTEDIT_T*) app;
	UINT32                	    status = 0;
	//if (u_strcmp(papp->filedir, L"/"))
	//{
	//FBLevelUp(papp->filedir);
	//FindFile(papp->filedir,L"*",app);
	//UpdateList(ev_st, app, 1);
    //UIS_Refresh();
	//}else {
	//if(papp->setmode==MAIN_MAP||papp->setmode==MAIN_PIC)
	papp->setmode=0;
	papp->d_true=TRUE;
	status = APP_UtilChangeState(HE_STATE_MAIN, ev_st, app );
	//}
	return status;
}
UINT32 UpdateList( EVENT_STACK_T *ev_st,  void *app, UINT32 sItem )
{
	APP_TXTEDIT_T			*papp = (APP_TXTEDIT_T*) app;

	if (sItem != 0) {
        dbg("Update List", NULL);

        DRM_SetResource( Resources[RES_LIST_CAPTION], (void*)papp->filedir, (u_strlen(papp->filedir)+1)*sizeof(WCHAR));

            APP_UtilAddEvUISListChange( ev_st,
                                    app,
                                    0, // = 0
                                    sItem,
                                    papp->cont,
                                    TRUE,
                                    2,          // = 2
                                    FBF_LEAVE,
                                    0,
                                    NULL );	

            UIS_HandleEvent( papp->apt.dialog,  ev_st );
    }
			
	
	return RESULT_OK;
}
UINT32 FBLevelUp( WCHAR* uri )
{
	UINT32          i;
	if (uri[u_strlen(uri)-1] == '/') uri[u_strlen(uri)-1] = 0;
		for (i=u_strlen(uri)-1; i > 0 ; i--)
			{
				if (uri[i] == '/')
					{
						break;
					}
					else
					{
					uri[i] = 0;
					}
			}
	return RESULT_OK;
}
UINT32 fbKeypress( EVENT_STACK_T *ev_st,  void *app )
{    
	APP_TXTEDIT_T           *papp = (APP_TXTEDIT_T*)app;
	EVENT_T     *event = AFW_GetEv(ev_st);
	UINT32                	    status = RESULT_OK;
	APP_ConsumeEv(ev_st, app);
	if (papp->filedir[0]=='/'&&papp->filedir[1]==0&&papp->setmode!=MAIN_PIC)
	return RESULT_OK;
	if(papp->setmode==MAIN_MAP)
	return RESULT_OK;
	if(event->data.key_pressed==KEY_1)
	{
	if(papp->setmode==MAIN_PIC)
	{
	papp->setmode=0;
	r_pic=FALSE;
	papp->d_true=TRUE;
	saveset(app);
	status = APP_UtilChangeState(HE_STATE_MAIN, ev_st, app );
	}
	else
	{
	u_strcpy(papp->openfile, papp->filedir);
	papp->setmode=MAIN_NEW;
	status = APP_UtilChangeState(HE_STATE_GOTO, ev_st, app );
	}
	}

	return status;
}
UINT32 fHandleNavigate( EVENT_STACK_T * ev_st, void * app )
{
	//APP_TXTEDIT_T			*papp = (APP_TXTEDIT_T*) app;
	EVENT_T *		event = AFW_GetEv(ev_st);
	
	f_pos[f_posid] = event->data.index;
	
	return RESULT_OK;
}

