package com.ekexiu.portal.service;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.jfw.apt.annotation.Autowrie;
import org.jfw.apt.annotation.DefaultValue;
import org.jfw.apt.annotation.Nullable;
import org.jfw.apt.web.annotation.Path;
import org.jfw.apt.web.annotation.operate.Get;
import org.jfw.apt.web.annotation.operate.Post;
import org.jfw.apt.web.annotation.operate.Put;
import org.jfw.apt.web.annotation.param.JdbcConn;
import org.jfw.apt.web.annotation.param.PathVar;
import org.jfw.apt.web.annotation.param.RequestBody;
import org.jfw.util.StringUtil;

import com.ekexiu.portal.dao.OrgDao;
import com.ekexiu.portal.po.Organization;

@Path("/org")
public class OrgService {
	
	private String defaultOrgType;
	
	
	@Autowrie
	private ImageService imageService;
	@Autowrie
	private OrgDao orgDao;
	
	public ImageService getImageService() {
		return imageService;
	}

	public void setImageService(ImageService imageService) {
		this.imageService = imageService;
	}

	public OrgDao getOrgDao() {
		return orgDao;
	}

	public void setOrgDao(OrgDao orgDao) {
		this.orgDao = orgDao;
	}
	

	public String getDefaultOrgType() {
		return defaultOrgType;
	}

	public void setDefaultOrgType(String defaultOrgType) {
		this.defaultOrgType = defaultOrgType;
	}

	@Post
	@Path
	public void insert(@JdbcConn(true) Connection con,Organization organization) throws SQLException 
	{
		organization.setId(StringUtil.buildUUID());
		if(organization.getOrgType()== null) organization.setOrgType(this.defaultOrgType);
		this.orgDao.insert(con, organization);
	}
	
	
	@Put
	@Path
	public void update(@JdbcConn(true) Connection con,@RequestBody Organization organization) throws SQLException{
		this.orgDao.update(con, organization);
	}
	
	@Get
	@Path("/{id}")
	public Organization query(@JdbcConn(false) Connection con ,@PathVar String id)throws SQLException{
		return this.orgDao.query(con, id);
	}
	
	@Get
	@Path("/qa")
	public List<Organization> query(@JdbcConn(false) Connection con )throws SQLException{
		return this.orgDao.query(con);
	}
	@Get
	@Path("/lq")
	public List<Organization> query(@JdbcConn Connection con ,@Nullable String name,@DefaultValue("5") int rows) throws SQLException
	{
		if(name==null) name = "%";
		else name="%"+name+"%";
		return this.orgDao.limitQuery(con, name, rows);
	}
	public String createOrganization(Connection con, String orgName) throws SQLException, IOException {
		String id = StringUtil.buildUUID();
		Organization org = new Organization();
		org.setId(id);
		org.setName(orgName);
		org.setOrgType(this.defaultOrgType);
		try {
			orgDao.insert(con, org);
			this.imageService.saveDefaultOrgLogo(id);
		} catch (SQLException e) {
			if ("23505".equals(e.getSQLState())) {
				con.rollback();
				id = orgDao.queryByName(con, orgName);
				if (id == null)
					throw new RuntimeException("not fonud  with query organization by name");
				return id;
			}
			throw e;
		}
		return id;
	}
	
}
