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

import com.bocloud.common.model.Pager;
import com.bocloud.common.model.Param;
import com.bocloud.common.model.SimpleBean;
import com.bocloud.common.utils.Common;
import com.bocloud.common.utils.MapTools;
import com.bocloud.database.core.intf.impl.BasicGenericDao;
import com.bocloud.database.utils.QueryBuilder;
import com.bocloud.ims.entity.resource.f5.BiProfile;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author kyw
 */
@Repository("f5BiProfileRepository")
public class F5BiProfileRepository extends BasicGenericDao<BiProfile, Long> {

    public F5BiProfileRepository(JdbcTemplate jdbcTemplate, NamedParameterJdbcTemplate npJdbcTemplate) {
        super(jdbcTemplate, npJdbcTemplate);
    }

    public List<BiProfile> list(int page, int rows, List<Param> params, Map<String, String> sorter, Long vendorId,
                                String category, String protocolProfileServerCategory, Boolean isFallbackPersistence) throws Exception {
        String sql = "select a.*,bp.name as partition_name, IFNULL(c.name,'(none)') AS parent_profile_name from bi_profile a left join bi_partition bp on a.partition_id = bp.id LEFT JOIN ( SELECT * FROM bi_profile b WHERE is_deleted = 0 AND b.vendor_id = :vendorId GROUP BY b.id) c ON  a.parent_profile_id = c.id where a.is_deleted = 0 AND a.vendor_id = :vendorId ";
        Map<String, Object> paramMap = QueryBuilder.getParam(params);
        paramMap.put("vendorId", vendorId);
        if (null != category) {
            sql += " and a.category like :category ";
            paramMap.put("category", category + "%");
        }
        if (null != protocolProfileServerCategory) {
            switch (protocolProfileServerCategory) {
                case "tcp":
                    sql += " and a.category in('profile-tcp','profile-sctp') or a.name = 'udp' ";
                    break;
                case "udp":
                    sql += " and a.category in('profile-udp') or a.name = 'tcp' ";
                    break;
                case "stcp":
                    sql += " and a.category in('profile-tcp','profile-sctp') ";
                    break;
                default:
                    break;
            }
        }
        if (null != isFallbackPersistence) {
            if (isFallbackPersistence) {
                sql += " and (a.category IN ('persistence-source-addr', 'persistence-dest-addr')OR a.name IN ('dest_addr', 'source_addr')) ";
            }
        }
        sql = QueryBuilder.buildRaw(sql, new Pager(page, rows, params, sorter), "a");
        return this.list(BiProfile.class, sql, paramMap);
    }

    public List<SimpleBean> list(List<Param> params, Map<String, String> sorter, Long vendorId, String category,
                                 String protocolProfileServerCategory, Boolean isFallbackPersistence) throws Exception {
        String sql = "select b.id,b.name from bi_profile b where b.is_deleted = 0 AND b.vendor_id = :vendorId ";
        Map<String, Object> paramMap = QueryBuilder.getParam(params);
        paramMap.put("vendorId", vendorId);
        if (null != category) {
            sql += " and b.category like :category ";
            paramMap.put("category", category + "%");
        }
        if (null != protocolProfileServerCategory) {
            switch (protocolProfileServerCategory) {
                case "tcp":
                    sql += " and b.category in('profile-tcp','profile-sctp') or b.name = 'udp' ";
                    break;
                case "udp":
                    sql += " and b.category in('profile-udp') or b.name = 'tcp' ";
                    break;
                case "stcp":
                    sql += " and b.category in('profile-tcp','profile-sctp') ";
                    break;
                default:
                    break;
            }
        }
        if (null != isFallbackPersistence) {
            if (isFallbackPersistence) {
                sql += " and (b.category IN ('persistence-source-addr', 'persistence-dest-addr')OR b.name IN ('dest_addr', 'source_addr')) ";
            }
        }
        sql = QueryBuilder.buildRaw(sql, new Pager(1, Integer.MAX_VALUE, params, sorter), "b");
        List<BiProfile> listBiProfile = this.list(BiProfile.class, sql, paramMap);
        List<SimpleBean> beans = new ArrayList<SimpleBean>();
        for (BiProfile biProfile : listBiProfile) {
            beans.add(new SimpleBean(biProfile.getId(), biProfile.getName()));
        }
        return beans;
    }

    public int count(List<Param> params, Long vendorId, String category, String protocolProfileServerCategory,
                     Boolean isFallbackPersistence) throws Exception {
        String sql = "select count(1) from bi_profile a where a.is_deleted = 0 AND a.vendor_id = :vendorId ";
        Map<String, Object> paramMap = QueryBuilder.getParam(params);
        paramMap.put("vendorId", vendorId);
        if (null != category) {
            sql += " and a.category like :category ";
            paramMap.put("category", category + "%");
        }
        sql = QueryBuilder.buildRaw(sql, params, null, "a");
        if (null != protocolProfileServerCategory) {
            switch (protocolProfileServerCategory) {
                case "tcp":
                    sql += " and a.category in('profile-tcp','profile-sctp') or a.name = 'udp' ";
                    break;
                case "udp":
                    sql += " and a.category in('profile-udp') or a.name = 'tcp' ";
                    break;
                case "sctp":
                    sql += " and a.category in('profile-tcp','profile-sctp') ";
                    break;
                default:
                    break;
            }
        }
        if (null != isFallbackPersistence) {
            if (isFallbackPersistence) {
                sql += " and (a.category IN ('persistence-source-addr', 'persistence-dest-addr')OR a.name IN ('dest_addr', 'source_addr')) ";
            }
        }
        return this.countQuery(sql, paramMap).intValue();
    }

    public boolean remove(Long id, Long userId) throws Exception {
        String sql = "update bi_profile set is_deleted = 1, gmt_modify = :gmtModify, mender_id = :menderId where id = :id";
        Map<String, Object> params = MapTools.simpleMap("id", id);
        params.put("menderId", userId);
        params.put("gmtModify", new Date());
        return this.execute(sql, params) > 0;
    }

    public BiProfile query(Long id) throws Exception {
        String sql = "select b.name as partition_name,a.* from bi_profile a left join bi_partition b on a.partition_id = b.id where a.id =:id and a.is_deleted = 0";
        Map<String, Object> param = MapTools.simpleMap(Common.ID, id);
        List<BiProfile> listBiProfile = this.list(BiProfile.class, sql, param);
        if (listBiProfile.isEmpty()) {
            return null;
        }
        return listBiProfile.get(0);
    }

    public boolean removeByVendor(Long vendorId, Long userId) throws Exception {
        String sql = "update bi_profile set is_deleted = 1, gmt_modify = :gmtModify ,mender_id = :menderId where is_deleted = 0 and vendor_id = :vendorId";
        Map<String, Object> params = MapTools.simpleMap("vendorId", vendorId);
        params.put("menderId", userId);
        params.put("gmtModify", new Date());
        return this.execute(sql, params) > 0;
    }

    public boolean existName(String name, Long vendorId, Long partitionId) throws Exception {
        String sql = "select a.* from bi_profile a where a.is_deleted = 0 and a.name = :name AND a.vendor_id = :vendorId and partition_id = :partitionId ";
        Map<String, Object> paramMap = MapTools.simpleMap("name", name);
        paramMap.put("vendorId", vendorId);
        paramMap.put("partitionId", partitionId);
        List<BiProfile> listBiProfile = this.list(BiProfile.class, sql, paramMap);
        if (listBiProfile.isEmpty()) {
            return false;
        }
        return true;
    }

    public BiProfile queryParentId(Long parentProfileId, Long vendorId) throws Exception {
        String sql = "select * from bi_profile where parent_profile_id =:parentProfileId and is_deleted = 0 AND vendor_id = :vendorId ";
        Map<String, Object> param = MapTools.simpleMap("parentProfileId", parentProfileId);
        param.put("vendorId", vendorId);
        List<BiProfile> listBiProfile = this.list(BiProfile.class, sql, param);
        if (listBiProfile.isEmpty()) {
            return null;
        }
        return listBiProfile.get(0);
    }

    public BiProfile queryProxyMode(String proxyMode, Long vendorId, Long partitionId) throws Exception {
        String sql = "select * from bi_profile where proxy_mode =:proxyMode and is_deleted = 0 AND vendor_id = :vendorId and partition_id = :partitionId ";
        Map<String, Object> param = MapTools.simpleMap("proxyMode", proxyMode);
        param.put("vendorId", vendorId);
        param.put("partitionId", partitionId);
        List<BiProfile> listBiProfile = this.list(BiProfile.class, sql, param);
        if (listBiProfile.isEmpty()) {
            return null;
        }
        return listBiProfile.get(0);
    }

    public List<BiProfile> list(Long vendorId) throws Exception {
        String sql = "select * from bi_profile where is_deleted = 0 and vendor_id = :vendorId ";
        Map<String, Object> param = MapTools.simpleMap("vendorId", vendorId);
        return this.list(BiProfile.class, sql, param);
    }

    public BiProfile queryByName(String name, Long vendorId, Long partitionId) throws Exception {
        String sql = "select * from bi_profile where name =:name and is_deleted = 0 AND vendor_id = :vendorId and partition_id = :partitionId ";
        Map<String, Object> param = MapTools.simpleMap(Common.NAME, name);
        param.put("vendorId", vendorId);
        param.put("partitionId", partitionId);
        List<BiProfile> listBiProfile = this.list(BiProfile.class, sql, param);
        if (listBiProfile.isEmpty()) {
            return null;
        }
        return listBiProfile.get(0);
    }

}
