package com.mobvista.apptag.mapper;

import com.mobvista.apptag.entity.Storage;
import com.mobvista.apptag.entity.TagResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * @author wangjf
 */

public interface StorageDao {

    @Insert("REPLACE INTO storage(package_name,app_name,platform,tag,update_time,user_id) VALUES(#{packageName}, #{appName}, #{platform}, #{tag}, #{updateTime}, #{userId})")
    boolean save(Storage storage);

    @Select("SELECT * FROM storage WHERE package_name = #{packageName}")
    @Results({@Result(property = "packageName", column = "package_name"),
            @Result(property = "appName", column = "app_name"),
            @Result(property = "platform", column = "platform"),
            @Result(property = "tag", column = "tag"),
            @Result(property = "updateTime", column = "update_time")})
    Storage find(String packageName);

    @SelectProvider(type = ListMapperProvider.class, method = "list")
    @Results({@Result(property = "packageName", column = "package_name"),
            @Result(property = "appName", column = "app_name"),
            @Result(property = "platform", column = "platform"),
            @Result(property = "tag", column = "tag"),
            @Result(property = "updateTime", column = "update_time")})
    List<Storage> list(String search);

    class ListMapperProvider {
        public String list(String search) {
            String sql = "SELECT * FROM storage";
            if (StringUtils.isNotBlank(search)) {
                sql += " WHERE LOWER(package_name) LIKE '%" + search + "%'";
            }
            return sql;
        }
    }

    @SelectProvider(type = CountMapperProvider.class, method = "count")
    int count(String search);

    class CountMapperProvider {
        public String count(String search) {
            String sql = "SELECT COUNT(1) FROM storage";
            if (StringUtils.isNotBlank(search)) {
                sql += " WHERE LOWER(package_name) LIKE '%" + search + "%'";
            }
            return sql;
        }
    }
}