import { readFile, writeFile } from "fs";

import { Article, CardItem, LeanArticle, LeanMCMCard, MCMCard } from "./types";

export async function asyncLoadJSON<T>(filename: string): Promise<T> {
  return new Promise((resolve, reject) => {
    readFile(filename, "utf8", (err, data) => {
      if (err) {
        return reject(err);
      }
      resolve(JSON.parse(data));
    });
  });
}

export async function asyncSaveJSON(
  filename: string,
  data: any
): Promise<void> {
  return new Promise((resolve, reject) => {
    writeFile(filename, JSON.stringify(data), {}, err => {
      if (err) {
        return reject(err);
      }
      resolve();
    });
  });
}

export function leanCard(card: MCMCard): LeanMCMCard {
  return {
    colorIdentity: card.colorIdentity,
    colors: card.colors,
    convertedManaCost: card.convertedManaCost,
    edhrecRank: card.edhrecRank,
    manaCost: card.manaCost,
    mcmId: card.mcmId,
    name: card.name,
    rarity: card.rarity,
    scryfallId: card.scryfallId,
    subtypes: card.subtypes,
    supertypes: card.supertypes,
    text: card.text,
    type: card.type,
    types: card.types,
    set: card.set
  };
}

export function leanArticle(article: Article): LeanArticle {
  return {
    idArticle: article.idArticle,
    language: article.language.languageName,
    comments: article.comments,
    price: article.price,
    count: article.count,
    condition: article.condition
  };
}

export function onlyUnique(value: CardItem, index: number, self: CardItem[]) {
  return self.findIndex(c => c.name == value.name) == index;
}
