package jp.co.y_net.amm.page;

import java.io.File;
import java.io.FilenameFilter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;

import jp.co.y_net.amm.AppSession;
import jp.co.y_net.amm.common.AppSendMail;
import jp.co.y_net.amm.common.AppSendMail.MailSetting;
import jp.co.y_net.amm.common.ResourceReader;
import jp.co.y_net.amm.common.SessionUsageListener;
import jp.co.y_net.amm.dao.Usr;
import jp.co.y_net.amm.service.Logincheck;
import jp.co.y_net.amm.service.Logincheck.LogincheckResult;

import org.apache.wicket.RestartResponseException;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.link.DownloadLink;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.PageableListView;
import org.apache.wicket.markup.html.navigation.paging.PagingNavigator;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.Model;

public class DashboardPage extends CommonFrameA {
	private static final long serialVersionUID = 1L;
	
	private static final DateFormat DF_YYYYMMDDHHMMSSSS = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.S");
	
    public DashboardPage() {
        
        /* 認証 */
        if(isSystemAdmin() == false && ResourceReader.getBooleanQuick("debug.mode") == false) {
            AppSession.get().returnPageClass = DashboardPage.class;
            throw new RestartResponseException(LoginPage.class);
        }
        
        /* フィードバックパネル */
        final WebMarkupContainer fbPanel = new FeedbackPanel("feedback");
        add(fbPanel);
        
        /* ログインフォーム領域 ------------------------------------------------------------------------------------- */
        WebMarkupContainer divLogin = new WebMarkupContainer("divLogin") {
            @Override
            public boolean isVisible() {
                //return AppSession.isLogin() == false;
                return true;
            }
        };
        add(divLogin);
        
        
        final Model<String> modelChallengestringA = Model.of(challengestring.execute());
        final TextField<String> textChallenge = new TextField<String>("textChallenge", modelChallengestringA);
        final TextField<String> textLoginId = new TextField<String>("textLoginId", Model.of(""));
        final TextField<String> textChallengeResponse = new TextField<String>("textChallengeResponse", Model.of(""));

        
        /* ログイン */
        Button btnLogin = new Button("btnLogin");
        
        Form<Void> form =new Form<Void>("form") {
            @Override
            public boolean isVisible() {
                //return AppSession.isLogin() == false;
                return true;
            }
            @Override
            public void onSubmit() {
                /* ログイン処理 */
                
                String challengestringA = modelChallengestringA.getObject();
                String loginidB = textLoginId.getValue();
                String cresE = textChallengeResponse.getValue();
                
                
                /* ------------------------ */
                
                LogincheckResult checkresult = logincheck.executeFromApi(loginidB, cresE, challengestringA); // ここではAPI呼び出しと同等にする
                
                if(0 == checkresult.errorCode) {
                    /* 認証成功 */

                    /* セッションへ登録 */
                    Usr usr = usrDao.getByLoginid(loginidB);
                    AppSession.get().setLoginUser(usr);
                    
                    /* jsessionidの変更（セッション固定化攻撃対策）*/
                    AppSession.get().replaceSession();
                    
                    if(AppSession.get().returnPageClass != null) {
                        /* 呼び出し元が設定されている場合 */
                        setResponsePage(AppSession.get().returnPageClass, AppSession.get().returnPageParameters);
                    } else {
                        /* 呼び出し元が設定されていない場合 */
                        //setResponsePage(getApplication().getHomePage());
                        setResponsePage(getPage());
                    }
                    
                } else {
                    error(Logincheck.errorMemo.get(checkresult.errorCode) + "/" + Logincheck.errorMessage.get(checkresult.errorCode) );
                }
            }
        };
        divLogin.add(form);
        form.add(textChallenge);
        form.add(textLoginId);
        form.add(textChallengeResponse);
        form.add(btnLogin);
        
        /*
         * メール送信テスト
         */
        WebMarkupContainer divSendMail = new WebMarkupContainer("divSendMail");
        add(divSendMail);
        {
            Form<Void> formMail =new Form<Void>("form");
            divSendMail.add(formMail);
            
            final TextField<String> mail = new TextField<String>("mail", Model.of(""));
            formMail.add(mail);
            
            final Button btnSubmit = new Button("btnSubmit"){
                @Override
                public void onSubmit() {
                    MailSetting setting = new MailSetting();
                    setting.setTemplate(ResourceReader.getText("message/mail.test"));
                    setting.setMailTo(mail.getValue());
                    boolean sendmailrsult = AppSendMail.send(setting);
                    if(sendmailrsult == false) {
                        error("メールの送信に失敗しました。");
                    }
                   
                }
            };
            formMail.add(btnSubmit);
        }
        
        /* ログ取得 */
        WebMarkupContainer cntLogs = new WebMarkupContainer("cntLogs") {
            @Override
            public boolean isVisible() {
                //return AppSession.get().isLogin();
                return true;
            }
        };
        add(cntLogs);
        final IModel<List<File>> logs = new LoadableDetachableModel<List<File>>() {
            @Override
            protected List<File> load() {
                File dir = new File(System.getProperty("catalina.base"), "logs");
                if(dir.exists() == false) {
                    return new ArrayList<File>();
                }
                File[] aryLogs = dir.listFiles(new FilenameFilter() {
                    @Override
                    public boolean accept(File dir, String name) {
                        return (name.startsWith("AMMLog") && name.endsWith(".log"));
                    }
                });
                List<File> logs = new ArrayList<File>();
                for(File l: aryLogs) {
                    logs.add(l);
                }
                Collections.sort(logs, new Comparator<File>() {
                    @Override
                    public int compare(File o1, File o2) {
                        return Long.valueOf(o1.lastModified())
                                .compareTo(
                                        Long.valueOf(o2.lastModified())
                                        ) * -1;
                    }
                });
                return logs;
            }
        };
        final PageableListView<File> listview = new PageableListView<File>("lvLog", logs, 5) {
            private static final long serialVersionUID = 1L;
            @Override
            protected void populateItem(ListItem<File> item) {
                File log = item.getModelObject();
                
                DownloadLink lnkLog = new DownloadLink("lnkLog", log);
                
                lnkLog.add(new Label("log", log.getAbsolutePath()));
                item.add(lnkLog);
            }
        };
//        listview.setReuseItems(true);
        cntLogs.add(listview);
        PagingNavigator navigator = new PagingNavigator("paging", listview);
        cntLogs.add(navigator);
        
        
        /* セッション利用状況 */
        StringBuilder sb = new StringBuilder();
        
        int i = 0;
        for (Map.Entry<String, Date> e: SessionUsageListener.map.entrySet()) {
            
            String startTime = DF_YYYYMMDDHHMMSSSS.format(e.getValue());
            String sessinId = e.getKey();
            
            sb.append(String.format("#%1$04d",i++ )+ ":" + startTime + "："+ sessinId + "\n");
        }
        if(i == 0) {
            sb.append("0件");
        }
        add(new Label("sessionusage", sb.toString()));
        
        
        /* 再表示 */
        BookmarkablePageLink<Void> lnkReload = new BookmarkablePageLink<Void>("lnkReload", DashboardPage.class);
        add(lnkReload);
        
    }

}
