package jp.sourceforge.shovel.action.impl;

import static jp.sourceforge.shovel.util.ShovelUtil.*;

import net.arnx.jsonic.JSON;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jp.sourceforge.shovel.action.IConflictForeignKeyAction;
import jp.sourceforge.shovel.entity.IUser;
import jp.sourceforge.shovel.form.IConflictForeignKeyForm;
import jp.sourceforge.shovel.service.IDirectoryService;
import jp.sourceforge.shovel.service.IShovelService;
import jp.sourceforge.shovel.util.ShovelUtil;

public class ConflictForeignKeyActionImpl implements IConflictForeignKeyAction {
    IConflictForeignKeyForm actionForm_;
    HttpServletRequest request_;
    HttpServletResponse response_;
    
    class JSONBean {
        String foreignKey_;
        boolean already_;
        boolean invalid_;
        
        public JSONBean(String foreignKey, boolean already, boolean invalid) {
            foreignKey_ = foreignKey;
            already_ = already;
            invalid_ = invalid;
        }
        
        public String getForeignKey() {
            return foreignKey_;
        }
        public boolean getAlready() {
            return already_;
        }
        public boolean getInvalid() {
            return invalid_;
        }
    }
    
    public String perform() throws Exception {
        String foreignKey = actionForm_.getForeignKey();
        int retval = ShovelUtil.validateUser(null, foreignKey, null, true);

        IDirectoryService directoryService = getDirectoryService();
        IUser user = directoryService.getLoginUser();
        //空なユーザ名は不正
        if (foreignKey != null && foreignKey.length() > 0) {
            long userId = actionForm_.getUserId();
            if (userId > 0) {
                user = directoryService.getUser(userId);
            }
            if (user == null || foreignKey.compareTo(user.getForeignKey()) == 0) {
                //元々のユーザ名
                user = null;
            } else {
                user = directoryService.getUser(foreignKey);
            }
        }
        String json = JSON.encode(new JSONBean(foreignKey, user != null, retval != VALIDATION));
        ServletOutputStream stream = response_.getOutputStream();
        stream.write(json.getBytes("UTF-8"));
        return null;
    }
    public void setConflictForeignKeyForm(IConflictForeignKeyForm actionForm) {
        actionForm_ = actionForm;
    }
    public IDirectoryService getDirectoryService() {
        return getShovelService().getDirectoryService();
    }
    public IShovelService getShovelService() {
        return (IShovelService)request_.getAttribute("shovelService");
    }
    public void setRequest(HttpServletRequest request) {
        request_ = request;
    }
    public void setResponse(HttpServletResponse response) {
        response_ = response;
    }
}
