package com.leanwo.activiti.rest.db;

import java.sql.SQLException;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.leanwo.activiti.db.AccountManagementService;
import com.leanwo.activiti.db.DatabaseService;
import com.leanwo.activiti.dto.BaseResponse;
import com.leanwo.activiti.util.LoginContextUtil;

@RestController
@RequestMapping("/workflow-system/DatabaseResource")
public class DatabaseResource {

    private static Logger logger = LoggerFactory.getLogger(DatabaseResource.class);
	@Inject
	private DatabaseService databaseService;

    @Inject
    private AccountManagementService accountManagementService; 

	/**
	 * 更新数据源
	 * @param accountId
	 * @return
	 * @throws SQLException 
	 */
	@RequestMapping(value = "/initWorkflowDatabase", method = RequestMethod.GET, produces = "application/json")
	public BaseResponse initWorkflowDatabase(@RequestParam(value = "accountId") Long accountId) throws SQLException {
        LoginContextUtil.setUseApplicationAccount(accountId);
        accountManagementService.loadAccountManagement(false);
        try {
            databaseService.schemaUpdate(accountId);
            return new BaseResponse(0, null);
        }catch(Exception ex) {
            logger.error("数据库升级失败。", ex);
            return new BaseResponse(1, "数据库升级失败。" + ex.getMessage());
        }
	}
	
}
