/*	DefaultComponentActionHandler.java

	Purpose:
		
	Description:
		
	History:
		2013/8/5 by Dennis

	Copyright (C) 2010 Potix Corporation. All Rights Reserved.
*/
package org.zkoss.zssex.ui.impl.ua;

import org.zkoss.image.AImage;
import org.zkoss.util.media.Media;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.event.SerializableEventListener;
import org.zkoss.zk.ui.event.UploadEvent;
import org.zkoss.zss.api.Range;
import org.zkoss.zss.api.Ranges;
import org.zkoss.zss.api.AreaRef;
import org.zkoss.zss.api.SheetOperationUtil;
import org.zkoss.zss.api.model.Sheet;
import org.zkoss.zss.api.model.Book.BookType;
import org.zkoss.zss.ui.UserActionContext;
import org.zkoss.zul.Fileupload;
/**
 * 
 * 
 * @author dennis
 *
 */
public class InsertPictureHandler extends AbstractObjectHandler {
	private static final long serialVersionUID = 2854009085197831214L;

	@Override
	protected boolean processAction(final UserActionContext ctx) {
		final Sheet sheet = ctx.getSheet();
		
		final AreaRef selection = ctx.getSelection();
		
		Range range = Ranges.range(sheet, selection.getRow(), selection.getColumn(), selection.getLastRow(), selection.getLastColumn());
		if(range.isProtected() && !range.getSheetProtection().isObjectsEditable()){
			showProtectMessage();
			return true;
		}
		
		Fileupload.get(1,new SerializableEventListener<UploadEvent>() {
			private static final long serialVersionUID = 767590813246792367L;

			public void onEvent(UploadEvent event) throws Exception {
				Media media = event.getMedia();
				doInsertPicture(ctx,media);
			}
		});
		return true;
	}
	
	protected boolean doInsertPicture(final UserActionContext ctx, final Media media) {
		if(media==null){
			return true;
		}
		if(!(media instanceof AImage) || SheetOperationUtil.getPictureFormat((AImage)media)==null){
			showWarnMessage(Labels.getLabel("zss.actionhandler.msg.cant_support_file", new Object[]{media==null?"":media.getName()}));
			return true;
		}
		
		final Sheet sheet = ctx.getSheet();
		final AreaRef selection = ctx.getSelection();
		Range range = Ranges.range(sheet, selection.getRow(), selection.getColumn(), selection.getLastRow(), selection.getLastColumn());
		
		SheetOperationUtil.addPicture(range,(AImage)media);
		return true;
	}

}
