package jp.agentec.abook.abv.ui.viewer.view;

import java.sql.Timestamp;

import jp.agentec.abook.abv.bl.acms.client.json.content.ActionInfoJSON;
import jp.agentec.abook.abv.bl.common.exception.NetworkDisconnectedException;
import jp.agentec.abook.abv.bl.common.log.Logger;
import jp.agentec.abook.abv.bl.data.ABVDataCache;
import jp.agentec.abook.abv.bl.dto.EnqueteDto;
import jp.agentec.abook.abv.bl.logic.AbstractLogic;
import jp.agentec.abook.abv.bl.logic.EnqueteLogic;
import jp.agentec.abook.abv.bl.websocket.MeetingManager;
import jp.agentec.abook.abv.launcher.android.R;
import jp.agentec.abook.abv.ui.common.dialog.ABookAlertDialog;
import jp.agentec.abook.abv.ui.common.util.ABVToastUtil;
import jp.agentec.abook.abv.ui.common.util.AlertDialogUtil;
import jp.agentec.abook.abv.ui.viewer.activity.ContentViewActivity;
import jp.agentec.adf.util.DateTimeUtil;

import org.json.adf.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Build;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

 
public class EnqueteLayout extends RelativeLayout {

	private static final float INIT_ALPHA = 1.0f;
	public static final int HALF_WIDTH = 340;

	public interface OnWebViewListener {
		void close();
		void Left();
		void Right();
		void TouchEvent();
		void DisallowMovePage();
	}

	protected static final String TAG = "EnqueteLayout";

	private Activity context; 
	private int mPageNum; 
	private OnWebViewListener webViewListener; 
	private long abEnqueteId; 
	
	private ImageButton btnExit;
	private ImageButton btnFontSmall;
	private ImageButton btnFontBig;
	
	private ImageButton btnLeft;
	private ImageButton btnRight;
	
	private ImageButton btnAlpha;
	
	private TextView alphaStart;
	private TextView alphaEnd;
	private TextView alphaText;
	
	private SeekBar alphaSeekBar;
	
	private boolean alphaFlag = false; //투명도 조절 Flag
	
	private EnqueteWebView mWebView = null;
	
	private LinearLayout seekLinear;
	private LinearLayout alphaLinear;
	
	private RelativeLayout btnLinear;
	
	private boolean webViewTouch = false;
	private boolean btnLinearTouch = false;
	private boolean seekLinearTouch = false;
	
	private View layoutView;
	
	//오서링 설문 지정시 해당 설문으로 이동수정
	private boolean pageStart;
	private MeetingManager meetingManager;
	private ActionInfoJSON actionInfoJSON;
	
	public EnqueteLayout(Context context, EnqueteWebView webView, final long contentId, int pageNum, ActionInfoJSON actionInfoJSON, String htmlPath, final int pixelWidth, boolean isFullScreen, final OnWebViewListener webViewListener) {
		super(context);

		this.context = (Activity) context;
		this.mPageNum = pageNum;
		this.webViewListener = webViewListener;
		this.actionInfoJSON = actionInfoJSON;
		this.abEnqueteId = actionInfoJSON.getEnqueteId();
		final long abObjectId = actionInfoJSON.getObjectId();
		final String abQuestionNo = actionInfoJSON.getQuestionNo();
		
		meetingManager = MeetingManager.getInstance();
		
		if (webView != null) {
			mWebView = webView;
		} else {
			mWebView = new EnqueteWebView(context);
			mWebView.getSettings().setJavaScriptEnabled(true);
			mWebView.setHorizontalScrollBarEnabled(true);
			mWebView.setVerticalScrollBarEnabled(true);
			mWebView.setAlpha((int) (255 * INIT_ALPHA)); // 80%->100%に変更
			mWebView.setOnTouchListener(new OnTouchListener() {
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					
					if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE || event.getAction() == MotionEvent.ACTION_UP) {
						
						if (webViewTouch && btnLinearTouch || webViewTouch && seekLinearTouch== true) {
							seekLinearTouch = false;
							btnLinearTouch = false;
							webViewListener.DisallowMovePage();
							webViewListener.TouchEvent();
							return true;
						}
						webViewListener.DisallowMovePage();
						webViewListener.TouchEvent();
					}
					return false;
				}
			});
			//ターゲットバージョン30以上からデフォルトがfalseに設定されている問題対応
			mWebView.getSettings().setAllowFileAccess(true);

			mWebView.loadUrl(htmlPath);
		}
		
		int layoutViewResId = isFullScreen? R.layout.enqute_webview_large: R.layout.enqute_webview_small;
		layoutView = ((Activity) context).getLayoutInflater().inflate(layoutViewResId, null);
		
		RelativeLayout.LayoutParams param2 = createParam(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        param2.addRule(RelativeLayout.ABOVE, R.layout.enqute_webview_large);
        param2.bottomMargin = 20;
        addView(mWebView, param2);
        
        RelativeLayout.LayoutParams param3 = createParam(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        param3.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        addView(layoutView, param3);
		
		seekLinear = (LinearLayout)findViewById(R.id.seek_linear);
		seekLinear.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {

				if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE || event.getAction() == MotionEvent.ACTION_UP) {
					webViewListener.DisallowMovePage();
					webViewListener.TouchEvent();
					seekLinearTouch = true;
					webViewTouch = true;
					return true;
				}
				return false;
			}
		});

		
		alphaLinear = (LinearLayout)findViewById(R.id.alpha_linear);
		alphaLinear.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				
				if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE || event.getAction() == MotionEvent.ACTION_UP) {
					webViewListener.DisallowMovePage();
					webViewListener.TouchEvent();
					seekLinearTouch = true;
					webViewTouch = true;
					return true;
				}
				return false;
			}
		});
		
		alphaText = (TextView)findViewById(R.id.alpha_text);
		alphaText.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				
				if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE || event.getAction() == MotionEvent.ACTION_UP) {
					webViewListener.DisallowMovePage();
					webViewListener.TouchEvent();
					return true;
				}		
				
				return false;
			}
		});
		
		alphaSeekBar = (SeekBar)findViewById(R.id.light_SeekBar);
		alphaSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				webViewListener.DisallowMovePage();
				webViewListener.TouchEvent();
			}
			
			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				webViewListener.DisallowMovePage();
				webViewListener.TouchEvent();
			}
			
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
				webViewListener.DisallowMovePage();
				webViewListener.TouchEvent();
				mWebView.setAlpha(progress);
	            if (meetingManager.isSendable()) {
	            	JSONObject json = new JSONObject();
					json.put(MeetingManager.ALPHA, (float)progress / 255);
	            	meetingManager.sendWs(MeetingManager.CMD_QUESTIONNAIREACTION, contentId, mPageNum, abObjectId, json);
	            }
			}
		});
		alphaSeekBar.setProgress((int) (alphaSeekBar.getMax() * INIT_ALPHA));

		alphaStart = (TextView)findViewById(R.id.number_start);
        alphaStart.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				
				if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE || event.getAction() == MotionEvent.ACTION_UP) {
					webViewListener.DisallowMovePage();
					webViewListener.TouchEvent();
					return true;
				}
				return false;
			}
		});
        
		alphaEnd = (TextView)findViewById(R.id.number_end);
		alphaEnd.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE || event.getAction() == MotionEvent.ACTION_UP) {
					webViewListener.DisallowMovePage();
					webViewListener.TouchEvent();
					return true;
				}
				return false;
			}
		});
		
		btnLinear = (RelativeLayout)findViewById(R.id.btn_linear);
		btnLinear.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE || event.getAction() == MotionEvent.ACTION_UP) {
					webViewListener.DisallowMovePage();
					webViewListener.TouchEvent();
					btnLinearTouch = true;
					webViewTouch = true;
					return true;
				}	
				return false;
			}
		});
		
		if (!isFullScreen) {
			configureLeftRightButton(webViewListener);
		}
		
		btnAlpha = (ImageButton)findViewById(R.id.light_btn);
		btnAlpha.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (alphaFlag == false) {
					seekLinear.setVisibility(VISIBLE);
					alphaStart.setVisibility(VISIBLE);
					alphaEnd.setVisibility(VISIBLE);
					alphaSeekBar.setVisibility(VISIBLE);
					alphaFlag = true;
				} else{
					
					seekLinear.setVisibility(GONE);
					alphaStart.setVisibility(GONE);
					alphaEnd.setVisibility(GONE);
					alphaSeekBar.setVisibility(GONE);
					alphaFlag = false;
				}
			}
		});
		
		btnAlpha.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE || event.getAction() == MotionEvent.ACTION_UP) {
					webViewListener.DisallowMovePage();
					webViewListener.TouchEvent();
				}
				return false;
			}
		});
		
		btnFontSmall = (ImageButton)findViewById(R.id.font_small);
		btnFontSmall.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				setFontSmall();
	            if (meetingManager.isSendable()) {
	            	JSONObject json = new JSONObject();
					json.put(MeetingManager.IS_BIG_FONT_SIZE, false);
	            	meetingManager.sendWs(MeetingManager.CMD_QUESTIONNAIREACTION, contentId, mPageNum, abObjectId, json);
	            }
			}
		});
		
		btnFontSmall.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE || event.getAction() == MotionEvent.ACTION_UP) {
					webViewListener.DisallowMovePage();
					webViewListener.TouchEvent();
				}
				return false;
			}
		});

		
		btnFontBig = (ImageButton)findViewById(R.id.font_big);
		btnFontBig.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				setFontBig();
	            if (meetingManager.isSendable()) {
	            	JSONObject json = new JSONObject();
					json.put(MeetingManager.IS_BIG_FONT_SIZE, true);
	            	meetingManager.sendWs(MeetingManager.CMD_QUESTIONNAIREACTION, contentId, mPageNum, abObjectId, json);
	            }
			}
		});
		
		btnFontBig.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE || event.getAction() == MotionEvent.ACTION_UP) {
					webViewListener.DisallowMovePage();
					webViewListener.TouchEvent();
				}
				return false;
			}
		});
		
		btnExit = (ImageButton)findViewById(R.id.research_exit);
		btnExit.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mWebView.clearCache(true);
				webViewListener.close();
			}
		});
		btnExit.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE || event.getAction() == MotionEvent.ACTION_UP) {
					webViewListener.DisallowMovePage();
					webViewListener.TouchEvent();
				}
				return false;
			}
		});
		
		mWebView.setWebViewClient(new WebViewClient() {
			//오서링 설문 지정시 해당 설문으로 이동수정
			@Override
			public void onPageFinished(WebView view, String url) {
				Logger.d(TAG, "abQuestionNo : " + abQuestionNo);
                if (pageStart) {
                    //クイズで回答可能回数1回設定した場合：クイズをやったことを確認するため答えたクイズをデータベースに保存する。
                    if (getActionInfoJSON().getActionType() == ActionInfoJSON.QUIZ_ACTION && getActionInfoJSON().getReplyLimit() == 1) {
                        EnqueteLogic enqueteLogic = AbstractLogic.getLogic(EnqueteLogic.class);
                        EnqueteDto dto = new EnqueteDto();
                        dto.abObjectId = abObjectId;
                        dto.abEnqueteId = abEnqueteId;
                        dto.contentId = contentId;
                        dto.param = "";
                        dto.replyDateStr = DateTimeUtil.getCurrentTimestamp();
                        dto.replyFlg = true;//replyFlg = trueの場合：新着更新ボタンを押した時にも送信しない。
                        enqueteLogic.insertEnquete(dto);
                    }
                } else {
                    mWebView.loadUrl("javascript:setResultSendType(true)");
                    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
                        mWebView.loadUrl("javascript:setAndroid403(true)");
                    }

                    if (!abQuestionNo.equals("0")) {
                        mWebView.loadUrl("javascript:initDisplay('" + abQuestionNo + "')");
                    }

                    pageStart = true;

                }
				callFixWidth();
				//試験の場合：結果送信しない設定した場合
				if (getActionInfoJSON().getActionType() == ActionInfoJSON.EXAM_ACTION && getActionInfoJSON().getSendResult() == 0) {
					callChangeButton();
				}
			}

			@Override
			public void onScaleChanged(WebView view, float oldScale, float newScale) {
				super.onScaleChanged(view, oldScale, newScale);
				callFixWidth();
			}

			protected void callFixWidth() {
				int htmlInputWidth = (int) (HALF_WIDTH * 0.7) ; 
				Logger.d(TAG, "htmlInputWidth : " + htmlInputWidth);
				StringBuffer javascript = new StringBuffer();
				javascript.append("javascript:jQuery(\":input:text\").not(\".notResize\").css(\"width\",\"" + htmlInputWidth + "px\").css(\"vertical-align\",\"middle\");");
				javascript.append("javascript:jQuery(\"textarea\").not(\".notResize\").css(\"width\",\"" + htmlInputWidth + "px\").css(\"font-size\",\"16px\");");
				javascript.append("javascript:jQuery(\":text\").not(\".notResize\").css(\"width\",\"" + htmlInputWidth + "px\");");

				mWebView.loadUrl(javascript.toString());
			}
			
			protected void callChangeButton() {
				Logger.d(TAG, "changeButton : ");
				mWebView.loadUrl("javascript:changeButton()");
			}
			
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				
				boolean isGotoNextScreen = true;////試験の場合：オフライン時 結果送信する場合且つオフライン時結果送信しない場合：結果画面に進ままない。
				boolean show_result = true; //試験の場合結果採点表示
				boolean send_result = true; //試験の場合：結果送信
				
				//試験の場合：結果画面非表示設定した場合：別の画面に呼び出す
				if (getActionInfoJSON().getActionType() == ActionInfoJSON.EXAM_ACTION && getActionInfoJSON().getShowResult() == 0) {
            		show_result = false;
            	} 
				
				//試験の場合：結果送信しない設定した場合
				if (getActionInfoJSON().getActionType() == ActionInfoJSON.EXAM_ACTION && getActionInfoJSON().getSendResult() == 0) {
					send_result = false;
				}
				
        		if (url.startsWith("abook-api")) {
        			if (ContentViewActivity.enqueteMap.containsKey(abEnqueteId)) {
        				//hashmap에 해당 앙케이트 아이디의 값 삭제
        				ContentViewActivity.enqueteMap.remove(abEnqueteId);
        			}
	            	Uri uri = Uri.parse(url);
	        		String param = uri.getQuery();
	            	Timestamp ts = DateTimeUtil.getCurrentTimestamp();
	            	boolean enResult;
	            	EnqueteLogic enqueteLogic = AbstractLogic.getLogic(EnqueteLogic.class);
	            	EnqueteDto dto = new EnqueteDto();
	            	dto.abObjectId = abObjectId;
	            	dto.abEnqueteId = abEnqueteId;
	            	dto.contentId = contentId;
	            	dto.param = param;
	            	dto.replyDateStr = ts;
	            	
					if (send_result) {
	            		try {
		            		//앙케이트 결과 값을 서버에 송신한다.
		            		//cs 를 넘겨받아서 처리
							enResult= enqueteLogic.enqueteReply(dto.contentId, dto.abObjectId, ts, dto.param);

                            //성공시 reply_flg 값을 true
                            dto.replyFlg = enResult;
							
		            	} catch(NetworkDisconnectedException ne){
		            		dto.replyFlg = false;
		            		Logger.e(TAG, "enqueteReply error", ne);
		            		
		            		//オフライン時試験結果送信しないサービスオプション設定した場合：アラート出す。次の画面に移動しない
							if (getActionInfoJSON().getActionType() == ActionInfoJSON.EXAM_ACTION && !ABVDataCache.getInstance().serviceOption.isTransmitExamAtOffline()) {
		            			ABVToastUtil.showMakeText(getContext(), getContext().getString(R.string.exam_message), Toast.LENGTH_LONG);
			            		show_result = false;
			            		isGotoNextScreen = false;
		            		}
		            		
		            	} catch(Exception e) {
		            		dto.replyFlg = false;
		            		Logger.e(TAG, "enqueteReply error", e);
							ABVToastUtil.showMakeText(getContext(), getContext().getString(R.string.ERROR), Toast.LENGTH_LONG);
		            	}
	            	} else {
	            		//試験結果送信しない設定した場合且つ回答可能回数1回設定した場合：試験をやったことを確認
	            		dto.replyFlg = true;
	            	}
	           
					if (isGotoNextScreen) {
						//アンケートの場合又は試験の場合：データベースに保存する。
						enqueteLogic.insertEnquete(dto);
						if (show_result) {
							//앙케이트 결과 송신 후 showEnd 호출
							mWebView.loadUrl("javascript:showEnd()");
		            	} else {
		            		mWebView.loadUrl("javascript:showMsgs()");
		            	}
					}
        		}
            	return true;
           }
        });
    }

	private void configureLeftRightButton(final OnWebViewListener webViewListener) {
		btnLeft = (ImageButton)findViewById(R.id.move_left);
		btnLeft.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				webViewListener.Left();
			}
		});
		
		btnLeft.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE || event.getAction() == MotionEvent.ACTION_UP) {
					webViewListener.DisallowMovePage();
					webViewListener.TouchEvent();
				}
				return false;
			}
		});
		
		btnRight = (ImageButton)findViewById(R.id.move_right);
		btnRight.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				webViewListener.Right();
			}
		});
		
		btnRight.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE || event.getAction() == MotionEvent.ACTION_UP) {
					webViewListener.DisallowMovePage();
					webViewListener.TouchEvent();
				}
				return false;
			}
		});
	}
	
	private RelativeLayout.LayoutParams createParam(int w, int h) {
        return new RelativeLayout.LayoutParams(w, h);
    }
	
	//앙케이트 기능 중 뒤로 가기 버튼을 눌렀을때 메시지 창을 보여준다.
	public void showEnqueteDialog() {
		ABookAlertDialog enqueteDialog = AlertDialogUtil.createAlertDialog(context, R.string.enquete);
		enqueteDialog.setMessage(R.string.enquete_alert_message);
		enqueteDialog.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});

		enqueteDialog.setPositiveButton(R.string.yes , new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				if (ContentViewActivity.enqueteMap.containsKey(abEnqueteId)) {
    				//hashmap에 해당 앙케이트 아이디의 값 삭제
    				ContentViewActivity.enqueteMap.remove(abEnqueteId);
    			}
				webViewListener.close();
			}
		});
		enqueteDialog.show();
	}
	
	public void setAlpha(int alpha) {
		mWebView.setAlpha(alpha);
	}
	
	public void right() {
		webViewListener.Right();
	}
	
	public void left() {
		webViewListener.Left();
	}
	
	public void close() {
		webViewListener.close();
	}
	
	public void setFontSmall() {
		mWebView.loadUrl("javascript:defaultFontSize()");
		btnFontSmall.setBackgroundResource(R.drawable.btn_small_font_on);
		btnFontBig.setBackgroundResource(R.drawable.btn_big_font_off);
	}

	public void setFontBig() {
		mWebView.loadUrl("javascript:largeFontSize()");
		btnFontSmall.setBackgroundResource(R.drawable.btn_small_font_off);
		btnFontBig.setBackgroundResource(R.drawable.btn_big_font_on);
	}

	public ActionInfoJSON getActionInfoJSON() {
		return actionInfoJSON;
	}

	public EnqueteWebView getWebView() {
		return mWebView;
	}
	
}
