const COLLECT_KEY = 'COLLECTION_LIST';
// export const isCollectionToken = ()=> {
//   const res = localStorage.getItem(COLLECT_KEY);
//   if(!res){
//     return false;
//   }
// }
export const getCollectionList = () => {
  const res = localStorage.getItem(COLLECT_KEY);
  if (!res) {
    return false;
  }
  try {
    const tokenList = JSON.parse(res);
    if (tokenList === false) {
      return [];
    }
    return tokenList;
  } catch (error) {
    console.log(error);
    return [];
  }
};
export const hasSet = (hash) => {
  const res = localStorage.getItem(COLLECT_KEY);
  if (!res) {
    return false;
  }
  try {
    const tokenList = JSON.parse(res);
    if (tokenList === false) {
      return false;
    }
    return tokenList.findIndex((item) => item.hash === hash) > -1;
  } catch (error) {
    return false;
  }
};
export const setCollection = (token) => {
  const res = localStorage.getItem(COLLECT_KEY);
  let list = [];
  if (res) {
    try {
      const tokenList = JSON.parse(res);
      list = [...tokenList];
    } catch (error) {}
  }
  if (list.findIndex((item) => item.hash == token.hash) === -1) {
    list = [token].concat(list);
    localStorage.setItem(COLLECT_KEY, JSON.stringify(list));
  }
};

export const deleteCollection = (tokenHash) => {
  const res = localStorage.getItem(COLLECT_KEY);
  if (res) {
    try {
      const tokenList = JSON.parse(res);
      if (tokenList !== false) {
        let index = tokenList.findIndex((item) => (item.hash === tokenHash));
        if (index >= 0) {
          tokenList.splice(index, 1);
          localStorage.setItem(COLLECT_KEY, JSON.stringify(tokenList));
        }
      }
    } catch (error) {}
  }
};
