package com.bocloud.ims.repository.resource.installation;

import com.bocloud.common.utils.MapTools;
import com.bocloud.ims.entity.resource.installation.ServerRaidCtrl;
import com.bocloud.ims.repository.resource.DiskRepository;
import com.bocloud.ims.repository.resource.MdiskRepository;
import com.bocloud.ims.repository.resource.common.EnhancedBaseRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

/**
 * Server RaidCtrl DAO接口实现
 *
 * @author lkx007
 */
@Repository("serverRaidCtrlDao")
public class ServerRaidCtrlRepository extends EnhancedBaseRepository<ServerRaidCtrl, Long> {
    @Autowired
    private ServerPciRepository serverPciRepository;
    @Autowired
    private DiskRepository diskRepository;
    @Autowired
    private MdiskRepository mdiskRepository;

    public ServerRaidCtrl query(long id) throws Exception {
        String sql = "select a.* from server_raid_ctrl a where a.id = :id";
        Map<String, Object> params = MapTools.simpleMap("id", id);
        List<ServerRaidCtrl> list = this.list(ServerRaidCtrl.class, sql, params);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    public List<ServerRaidCtrl> getBySid(long serverId) throws Exception {
        String sql = "select a.* from server_raid_ctrl a where a.server_id = :serverId";
        Map<String, Object> params = MapTools.simpleMap("serverId", serverId);
        List<ServerRaidCtrl> list = this.list(ServerRaidCtrl.class, sql, params);
        for (ServerRaidCtrl raidCtrl : list) {
            raidCtrl.setServerPci(serverPciRepository.query(raidCtrl.getPciId()));
            raidCtrl.setDiskGroups(mdiskRepository.getByControllerId(raidCtrl.getId()));
            raidCtrl.setDisks(diskRepository.getByControllerId(raidCtrl.getId()));
        }
        return list;
    }

    public ServerRaidCtrl get(long serverId, Integer controllerId) throws Exception {
        String sql = "select a.* from server_raid_ctrl a where a.server_id = :serverId and a.controller_id = :controllerId";
        Map<String, Object> params = MapTools.simpleMap("serverId", serverId);
        params.put("controllerId", controllerId);
        List<ServerRaidCtrl> list = this.list(ServerRaidCtrl.class, sql, params);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    public void removeBySid(long serverId) throws Exception {
        String sql = "delete from server_raid_ctrl where server_id = :serverId";
        Map<String, Object> params = MapTools.simpleMap("serverId", serverId);
        this.update(sql, params);
    }

    public void remove(long id) throws Exception {
        String sql = "delete from server_raid_ctrl where id = :id";
        Map<String, Object> params = MapTools.simpleMap("id", id);
        this.update(sql, params);
    }
}
