/*
 *
 * UNICON - The Console Chinese & I18N
 * Copyright (c) 1999-2000
 *
 * This file is part of UNICON, a console Chinese & I18N
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 * See the file COPYING directory of this archive
 * Author: see CREDITS
 */

#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <fcntl.h>
#include <signal.h>
#include <errno.h>
#include <termios.h>
#include <getopt.h>
#include <locale.h>
#include <libintl.h>
#include <math.h>
#include <assert.h>
#include <setjmp.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/resource.h>
#include <linux/fb.h>
#include <linux/keyboard.h>
#include <pthread.h>

#include <unistd.h>
#include <termios.h>
#include <sys/ioctl.h>
#include <linux/vt.h>
#include <linux/kd.h>

#include <ImmHzInput.hpp>
#include <UniKey.hpp>
#include <ConfigManager.hpp>

#define MAX_TTY         6
class CHzInputMain 
{
private:
    /* Low Interface */
    CUniKey *pCMyKey;
    CConfigManager *pMyConfig;
    CImmHzInput *pTtyHzInput[MAX_TTY]; 
    ImmServer_T ImmServer;
public:
    void DoSwitchLang (int tty, int coding);

public:
    CHzInputMain (char *szIpAddr, short port, int resize,
                  char *szConfigFile, int DefaultCoding);
    ~CHzInputMain ();
    void DoRun ();
    void FlushAllTty ();
};

CHzInputMain::CHzInputMain (char *szIpAddr, short port, int resize,
                            char *szConfigFile, int DefaultCoding)
{
    pCMyKey = new CUniKey ("/dev/unikey", resize);
    pMyConfig = new CConfigManager (szConfigFile, DefaultCoding);
    ImmServer = IMM_OpenClient (szIpAddr, port);
    for (int i = 0; i < MAX_TTY; i++)
    {
        pCMyKey->SetCurrentFont (i, DefaultCoding);
        pTtyHzInput[i] = new CImmHzInput (i + 1, 
              ImmServer, pMyConfig, pCMyKey);
    }
}

CHzInputMain::~CHzInputMain ()
{
    for (int i = 0; i < MAX_TTY; i++)
        delete pTtyHzInput[i];
    IMM_CloseClient (ImmServer);
    delete pMyConfig;
    delete pCMyKey;
}

int bExitInput = 0;
void CHzInputMain::DoRun ()
{
    TTY_KEY_T ui;
    int nCurTty = 0;

    do
    {
        pCMyKey->ReadKeys (&ui);
        if (ui.op & FLUSH_INPUTMETHOD)
        {
            int nTty = ui.nTty;
            DoSwitchLang (nTty + 1, ui.op >> 4);
            //usleep (200);
            pTtyHzInput[nCurTty]->RefreshInputArea ();
            continue;
        }
        nCurTty = ui.nTty;       
        if (ui.op & FLUSH_BOTTOM)
        {
            usleep (200);
            pTtyHzInput[nCurTty]->RefreshInputArea ();
            continue;
        }
        if (ui.nTotal != 0)
            pTtyHzInput[nCurTty]->KeyFilters (ui.buf, ui.nTotal);
    }
    while (bExitInput == 0);
}

void CHzInputMain::FlushAllTty ()
{
    for (int i = 0; i < MAX_TTY; i++)
        pTtyHzInput[i]->DoFlush (); 
}

void CHzInputMain::DoSwitchLang (int tty, int coding)
{
    // printf ("DoSwitchLange::tty=%d, coding=%d\n", tty, coding);
    assert (tty >= 1 && tty <= MAX_TTY);
    pTtyHzInput[tty-1]->DoSwitchLang (tty, coding); 
}

int StartDaemon()
{
        pid_t pid;

        pid = fork();
        if(pid < 0) return 1;
        if(pid > 0) exit(0);    //parent
        //signal (SIGTERM, PinyinInputCleanup);
        return 0;
}

void SetIgnoreSignal ()
{
        signal( SIGTTOU, SIG_IGN );
        signal( SIGTTIN, SIG_IGN );

        //really for security, your terminal will be hungup
        signal( SIGINT, SIG_IGN );
        signal( SIGTSTP, SIG_IGN );
}

CHzInputMain *MyInput;

#ifdef __DLL_SUPPORT__
#ifdef  __cplusplus
extern "C" {
#endif
    extern long TCP_Connect (char *szIpAddr, short Port);
    extern int TCP_Disconnect (long handle);
    extern int LibOpen ();
    extern int LibRelease ();
#ifdef  __cplusplus
}
#endif

#endif

void our_exit (int i)
{
    extern int bExitInput;
    bExitInput = 1;
}

void WaitAllTtyStart ()
{
    int fd, i, n = 1;                                                               char buf[32];
    do
    {
        usleep (500);
        for (i = n; i <= 6; i++)
        {
            sprintf (buf, "/dev/tty%d", i);
            fd = open(buf, O_RDWR);
            if (fd != -1)
               n ++;
            close(fd);
        }
    }
    while (n <= 6);
}

int main (int argc, char **argv)
{
    int LocaleCode = XL_DB_GB, resize = -1;
    if (argc < 2)
    {
        printf ("Usage: %s <--gb | --gbk | --big5 | --jis | --kscm>  [--resize num] \n", argv[0]);
        exit (-1);
    }
    if (strcmp (argv[1], "--gb") == 0)
    {
        LocaleCode = XL_DB_GB;
	setlocale(LC_CTYPE, "zh_CN.GB2312");
    }
    else if (strcmp (argv[1], "--gbk") == 0)
    {
        LocaleCode = XL_DB_GBK;
	setlocale(LC_CTYPE, "zh_CN.GBK");
    }
    else if (strcmp (argv[1], "--big5") == 0)
    {
        LocaleCode = XL_DB_BIG5;
	setlocale(LC_CTYPE, "zh_TW");
    }
    else if (strcmp (argv[1], "--jis") == 0)
    {
        LocaleCode = XL_DB_JIS;
	setlocale(LC_CTYPE, "ja_JP");
    }
    else if (strcmp (argv[1], "--kscm") == 0)
    {
        LocaleCode = XL_DB_KSCM;
	setlocale(LC_CTYPE, "ko_KR");
    }
    else {
        printf ("bad parameter.....\n");
        exit (-1);
    }
    if (argv[2] != NULL && strcmp (argv[2], "--resize") == 0)
    {
        if (argv[3] != NULL)
            resize = atoi (argv[3]);
        else {
            printf ("bad parameter.....\n");
             exit (-1);
        }
    }
#ifdef __DLL_SUPPORT__
    LibOpen ();
#endif
    StartDaemon();
    WaitAllTtyStart ();
    SetIgnoreSignal ();
    signal (SIGTERM, our_exit);
    MyInput = new CHzInputMain ("127.0.0.1", 18030, resize, 
                  UNICON_LIB"/unicon.ini", LocaleCode);
    MyInput->DoRun ();
    MyInput->FlushAllTty ();
    delete MyInput;
    printf ("Unload Unicon Successfully.....\n");
#ifdef __DLL_SUPPORT__
    LibRelease ();
#endif
}

