/* -------------------------------------------- */
const TMRMapping = { 
      A1: { type: "cite", label: "Cité Vide"},
      B1: { type: "plaines", label: "Plaines d’Assorh"},
      C1: { type: "necropole", label: "Nécropole de Kroak"},
      D1: { type: "fleuve", label: "Fleuve"},
      E1: { type: "monts", label: "Monts de Kanaï"},
      F1: { type: "cite", label: "Cité Glauque"},
      G1: { type: "desolation", label: "Désolation de Demain"},
      H1: { type: "lac", label: "Lac d’Anticalme"},
      I1: { type: "plaines", label: "Plaines Grises"},
      J1: { type: "monts", label: "Monts Fainéants"},
      K1: { type: "cite", label: "Cité d’Onkause"},
      L1: { type: "fleuve", label: "Fleuve"},
      M1: { type: "cite", label: "Cité Jalouse"},
       
      A2: { type: "desert", label: "Désert de Mieux"},
      B2: { type: "collines", label: "Collines de Dawell"},
      C2: { type: "marais", label: "Marais Glignants"},
      D2: { type: "cite", label: "Cité de Frost"},
      E2: { type: "plaines", label: "Plaines de Fiask"},
      F2: { type: "lac", label: "Lac de Misère"},
      G2: { type: "marais", label: "Marais Nuisants"},
      H2: { type: "collines", label: "Collines de Parta"},
      I2: { type: "foret", label: "Forêt Fade"},
      J2: { type: "desert", label: "Désert de Poly"},
      K2: { type: "foret", label: "Forêt Tamée"},
      L2: { type: "fleuve", label: "Fleuve"},
      M2: { type: "necropole", label: "Nécropole de Logos"},

      A3: { type: "desolation", label: "Désolation de Demain"},
      B3: { type: "plaines", label: "Plaines de Rubéga"},
      C3: { type: "fleuve", label: "Fleuve"},
      D3: { type: "gouffre", label: "Gouffre d’Oki"},
      E3: { type: "foret", label: "Forêt d’Estoubh"},
      F3: { type: "fleuve", label: "Fleuve"},
      G3: { type: "gouffre", label: "Gouffre de Sun"},
      H3: { type: "foret", label: "Forêt de Ganna"},
      I3: { type: "monts", label: "Monts Grinçants"},
      J3: { type: "cite", label: "Cité Venin"},
      K3: { type: "plaines", label: "Plaines de Dois"},
      L3: { type: "lac", label: "Lac Laineux"},
      M3: { type: "monts", label: "Monts de Vdah"},

      A4: { type: "foret", label: "Forêt de Falconax"},
      B4: { type: "monts", label: "Monts Crâneurs"},
      C4: { type: "pont", label: "Pont de Giolii"},
      D4: { type: "lac", label: "Lac de Foam"},
      E4: { type: "plaines", label: "Plaines d’Orti"},
      F4: { type: "fleuve", label: "Fleuve"},
      G4: { type: "sanctuaire", label: "Sanctuaire Blanc"},
      H4: { type: "plaines", label: "Plaines de Psark"},
      I4: { type: "plaines", label: "Plaines de Xiax"},
      J4: { type: "collines", label: "Collines d’Encre"},
      K4: { type: "pont", label: "Pont de Fah"},
      L4: { type: "sanctuaire", label: "Sanctuaire Mauve"},
      M4: { type: "gouffre ", label: "Gouffre Grisant"},

      A5: { type: "plaines", label: "Plaines de Trilkh"},
      B5: { type: "collines", label: "Collines de Tanegy"},
      C5: { type: "marais", label: "Marais Flouants"},
      D5: { type: "fleuve", label: "Fleuve"},
      E5: { type: "monts", label: "Monts Brûlants"},
      F5: { type: "cite", label: "Cité de Panople"},
      G5: { type: "pont", label: "Pont d’Ik"},
      H5: { type: "desert", label: "Désert de Krane"},
      I5: { type: "desolation", label: "Désolation de Demain"},
      J5: { type: "marais", label: "Marais de Jab"},
      K5: { type: "fleuve", label: "Fleuve"},
      L5: { type: "collines", label: "Collines Suaves"},
      M5: { type: "cite", label: "Cité Rimarde"},

      A6: { type: "necropole", label: "Nécropole de Zniak"},
      B6: { type: "foret", label: "Forêt de Bust"},
      C6: { type: "cite", label: "Cité Pavois"},
      D6: { type: "fleuve", label: "Fleuve"},
      E6: { type: "sanctuaire", label: "Sanctuaire de Plaine"},
      F6: { type: "fleuve", label: "Fleuve"},
      G6: { type: "marais", label: "Marais Glutants"},
      H6: { type: "monts", label: "Monts Gurdes"},
      I6: { type: "necropole", label: "Nécropole de Xotar"},
      J6: { type: "lac", label: "Lac d’Iaupe"},
      K6: { type: "desolation", label: "Désolation de Demain"},
      L6: { type: "foret", label: "Forêt Gueuse"},
      M6: { type: "desolation", label: "Désolation de Demain"},

      A7: { type: "plaines", label: "Plaines de l’Arc"},
      B7: { type: "marais", label: "Marais Bluants"},
      C7: { type: "fleuve", label: "Fleuve"},
      D7: { type: "plaines", label: "Plaines d’A!a"},
      E7: { type: "foret", label: "Forêt de Glusks"},
      F7: { type: "fleuve", label: "Fleuve"},
      G7: { type: "cite", label: "Cité de Terwa"},
      H7: { type: "gouffre", label: "Gouffre de Kapfa"},
      I7: { type: "plaines", label: "Plaines de Troo"},
      J7: { type: "fleuve", label: "Fleuve"},
      K7: { type: "cite", label: "Cité de Kolix"},
      L7: { type: "gouffre", label: "Gouffre d’Episophe"},
      M7: { type: "desert", label: "Désert de Lave"},

      A8: { type: "gouffre", label: "Gouffre de Shok"},
      B8: { type: "fleuve", label: "Fleuve"},
      C8: { type: "foret", label: "Forêt Turmide"},
      D8: { type: "cite", label: "Cité d’Olak"},
      E8: { type: "plaines", label: "Plaines d’Iolise"},
      F8: { type: "lac", label: "Lac des Chats"},
      G8: { type: "plaines", label: "Plaines Sans Joie"},
      H8: { type: "foret", label: "Forêt d’Ourf"},
      I8: { type: "fleuve", label: "Fleuve"},
      J8: { type: "monts", label: "Monts Barask"},
      K8: { type: "desert", label: "Désert de Fumée"},
      L8: { type: "monts", label: "Monts Tavelés"},
      M8: { type: "plaines", label: "Plaines Lavées"},

      A9: { type: "collines", label: "Collines de Korrex"},
      B9: { type: "lac", label: "Lac de Lucre"},
      C9: { type: "monts", label: "Monts Tuméfiés"},
      D9: { type: "pont", label: "Pont d’Orx"},
      E9: { type: "fleuve", label: "Fleuve"},
      F9: { type: "plaines", label: "Plaines de Foe"},
      G9: { type: "desolation", label: "Désolation de Demain"},
      H9: { type: "collines", label: "Collines de Noirseul"},
      I9: { type: "fleuve", label: "Fleuve"},
      J9: { type: "marais", label: "Marais Gronchants"},
      K9: { type: "sanctuaire", label: "Sanctuaire Noir"},
      L9: { type: "collines", label: "Collines Cornues"},
      M9: { type: "necropole", label: "Nécropole de Zonar"},

      A10: { type: "sanctuaire", label: "Sanctuaire d’Olis"},
      B10: { type: "monts", label: "Monts Salés"},
      C10: { type: "marais", label: "Marais de Dom"},
      D10: { type: "fleuve", label: "Fleuve"},
      E10: { type: "gouffre", label: "Gouffre de Junk"},
      F10: { type: "marais", label: "Marais Zultants"},
      G10: { type: "cite", label: "Cité de Sergal"},
      H10: { type: "plaines", label: "Plaines Noires"},
      I10: { type: "lac", label: "Lac Wanito"},
      J10: { type: "fleuve", label: "Fleuve"},
      K10: { type: "plaines", label: "Plaines Jaunes"},
      L10: { type: "desert", label: "Désert de Nicrop"},
      M10: { type: "foret", label: "Forêt de Jajou"},

      A11: { type: "desolation", label: "Désolation de Demain"},
      B11: { type: "cite", label: "Cité de Brilz"},
      C11: { type: "pont", label: "Pont de Roï"},
      D11: { type: "desolation", label: "Désolation de Demain"},
      E11: { type: "lac", label: "Lac de Glinster"},
      F11: { type: "cite", label: "Cité de Noape"},
      G11: { type: "fleuve", label: "Fleuve"},
      H11: { type: "fleuve", label: "Fleuve"},
      I11: { type: "pont", label: "Pont de Yalm"},
      J11: { type: "plaines", label: "Plaines de Miltiar"},
      K11: { type: "cite", label: "Cité Tonnerre"},
      L11: { type: "collines", label: "Collines de Kol"},
      M11: { type: "cite", label: "Cité Crapaud"},

      A12: { type: "plaines", label: "Plaines Sages"},
      B12: { type: "fleuve", label: "Fleuve"},
      C12: { type: "lac", label: "Lac de Fricassa"},
      D12: { type: "collines", label: "Collines d’Huaï"},
      E12: { type: "monts", label: "Monts Ajourés"},
      F12: { type: "necropole", label: "Nécropole de Troat"},
      G12: { type: "plaines", label: "Plaines de Lufmil"},
      H12: { type: "collines", label: "Collines de Tooth"},
      I12: { type: "gouffre", label: "Gouffre Abimeux"},
      J12: { type: "cite", label: "Cité Folle"},
      K12: { type: "desolation", label: "Désolation de Demain"},
      L12: { type: "plaines", label: "Plaines Venteuses"},
      M12: { type: "collines", label: "Collines Révulsantes"},

      A13: { type: "fleuve", label: "Fleuve"},
      B13: { type: "gouffre", label: "Gouffre des Litiges"},
      C13: { type: "desert", label: "Désert de Neige"},
      D13: { type: "cite", label: "Cité Sordide"},
      E13: { type: "plaines", label: "Plaines de Xnez"},
      F13: { type: "foret", label: "Forêt des Cris"},
      G13: { type: "plaines", label: "Plaines Calcaires"},
      H13: { type: "desolation", label: "Désolation de Demain"},
      I13: { type: "monts", label: "Monts Bigleux"},
      J13: { type: "gouffre", label: "Gouffre de Gromph"},
      K13: { type: "foret", label: "Forêt de Kluth"},
      L13: { type: "monts", label: "Monts Dormants"},
      M13: { type: "plaines", label: "Plaines d’Anjou"},

      A14: { type: "collines", label: "Collines de Stolis"},
      B14: { type: "necropole", label: "Nécropole de Gorlo"},
      C14: { type: "foret", label: "Forêt de Bissam"},
      D14: { type: "sanctuaire", label: "Sanctuaire Plat"},
      E14: { type: "monts", label: "Monts de Quath"},
      F14: { type: "plaines", label: "Plaines Brisées"},
      G14: { type: "desert", label: "Désert de Sek"},
      H14: { type: "plaines", label: "Plaines Blanches"},
      I14: { type: "cite", label: "Cité Destituée"},
      J14: { type: "desert", label: "Désert de Sank"},
      K14: { type: "necropole", label: "Nécropole d’Antinéar"},
      L14: { type: "plaines", label: "Plaines de Jislith"},
      M14: { type: "desolation", label: "Désolation de Demain"},

      A15: { type: "cite", label: "Cité de Mielh"},
      C15: { type: "plaines", label: "Plaines de Toué"},
      E15: { type: "foret", label: "Forêt des Furies"},
      G15: { type: "plaines", label: "Plaines des Soupirs"},
      I15: { type: "monts", label: "Monts des Dragées"},
      K15: { type: "collines", label: "Collines Pourpres"},
      M15: { type: "cite", label: "Cité de Klana"}
    }

const rencontresTable = [
      {name:"Messagers des Rêves", data: { force: "2d4", ignorer: true, derober: true, refoulement: 1,
                                        cite: "01-25", sanctuaire: "01-25", plaines: "01-20", pont: "01-20", collines: "01-15", forêt: "01-15", monts: "01-10", desert: "01-10", fleuve: "01-05", 
                                        lac: "01-05", marais: "01-02", gouffre: "01-02", necropole: "00-00", desolation: "00-00" } },
      {name:"Passeur des Rêves",  data:  { force: "2d4", ignorer: true, derober: true, refoulement: 1,
                                          cite: "26-50", sanctuaire: "26-50", plaines: "21-40", pont: "21-40", collines: "16-30", forêt: "16-30", monts: "11-20", desert: "11-20", fleuve: "06-10", 
                                          lac: "06-10", marais: "03-04", gouffre: "03-04", necropole: "00-00", desolation: "00-00" } },
      {name:"Fleur des Rêves", data:     { force: "1d6", ignorer: true, derober: true, refoulement: 1,
                                        cite: "51-65", sanctuaire: "51-65", plaines: "41-55", pont: "41-55", collines: "31-42", forêt: "31-42", monts: "21-26", desert: "21-26", fleuve: "11-13", 
                                       lac: "11-13", marais: "05-05", gouffre: "05-05", necropole: "00-00", desolation: "00-00" } },
      {name:"Mangeur de Rêve", data:    { force: "1d6", ignorer: false, derober: true, refoulement: 1, 
                                       cite: "66-70", sanctuaire: "66-70", plaines: "56-60", pont: "56-60", collines: "43-54", forêt: "43-54", monts: "27-44", desert: "27-44", fleuve: "14-37", 
                                       lac: "14-37", marais: "06-29", gouffre: "06-29", necropole: "01-20", desolation: "01-20" } },
      {name:"Changeur de Rêve", data:   { force: "2d6", ignorer: false, derober: true, refoulement: 1, 
                                       cite: "71-80", sanctuaire: "71-80", plaines: "61-75", pont: "61-75", collines: "55-69", forêt: "55-69", monts: "45-59", desert: "45-59", fleuve: "38-49", 
                                       lac: "38-49", marais: "30-39", gouffre: "30-39", necropole: "21-30", desolation: "21-30" } },
      {name:"Briseur de Rêve", data:    { force: "2d6", ignorer: false, derober: true, refoulement: 1, 
                                       cite: "81-85", sanctuaire: "81-85", plaines: "76-82", pont: "76-82", collines: "70-82", forêt: "70-82", monts: "60-75", desert: "60-75", fleuve: "50-65", 
                                       lac: "50-65", marais: "40-60", gouffre: "40-60", necropole: "31-50", desolation: "31-50" } },
      {name:"Reflet d'ancien Rêve", data:  { force: "2d6", ignorer: false, derober: true, refoulement: 1,
                                       cite: "86-90", sanctuaire: "86-90", plaines: "83-88", pont: "83-88", collines: "83-88", forêt: "83-88", monts: "76-85", desert: "76-85", fleuve: "66-79", 
                                       lac: "66-79", marais: "61-75", gouffre: "61-75", necropole: "51-65", desolation: "51-65" } },
      {name:"Tourbillon blanc", data:  { force: "2d6", ignorer: false, derober: true, refoulement: 1,
                                       cite: "91-94", sanctuaire: "91-94", plaines: "89-93", pont: "89-93", collines: "89-93", forêt: "89-93", monts: "86-92", desert: "86-92", fleuve: "80-89", 
                                       lac: "80-89", marais: "76-86", gouffre: "76-86", necropole: "66-80", desolation: "66-80" } },
      {name:"Tourbillon noir", data:   { force: "2d8", ignorer: false, derober: true, refoulement: 1, 
                                      cite: "95-97", sanctuaire: "95-97", plaines: "94-97", pont: "94-97", collines: "94-97", forêt: "94-97", monts: "93-97", desert: "93-97", fleuve: "90-97", 
                                      lac: "90-97", marais: "87-97", gouffre: "90-97", necropole: "81-97", desolation: "81-97" } },
      {name:"Rêve de Dragon", data:   { force: "1d7", ignorer: false, derober: true, refoulement: 2, 
                                       cite: "98-00", sanctuaire: "98-00", plaines: "98-00", pont: "98-00", collines: "98-00", forêt: "98-00", monts: "98-00", desert: "98-00", fleuve: "98-00", 
                                       lac: "98-00", marais: "98-00", gouffre: "98-00", necropole: "98-00", desolation: "98-00" } } 
      ]

/* -------------------------------------------- */
export class TMRUtility  {

  /* -------------------------------------------- */
  static convertToTMRCoord( x, y )
  {
    y = y + 1
    let letterX = String.fromCharCode(65+x);
    return letterX+y
  }

  /* -------------------------------------------- */
  static convertToCellCoord( coordTMR )
  {
    let x = coordTMR.charCodeAt(0) - 65;
    let y = coordTMR.substr(1) - 1;
    return {x: x, y: y}
  }
  
  /* -------------------------------------------- */
  static getTMRDescription( coordTMR)
  {
    return TMRMapping[coordTMR];
  }
  
  /* -------------------------------------------- */
  static rencontreTMRRoll( coordTMR, cellDescr ) 
  {
    let val = new Roll("d100").roll().total;
    //console.log("Rencontre !!!!", val, coordTMR, cellDescr);
    
    for( let renc of rencontresTable) {
      let scoreDef = renc.data[cellDescr.type];
      let min = scoreDef.substr(0,2);
      let max = scoreDef.substr(3,2);
      //console.log(val, scoreDef, min, max);
      if ( val >= min && val <= max) {
        return renc;
      }
    }
  }
  /* -------------------------------------------- */
  static getRandomLocationType( coordTMR ) {
    let descr = this.getTMRDescription( coordTMR );
    // TODO random get same type
    
  }
  
  /* -------------------------------------------- */
  static async  processRencontreReussite( actor, rencontre ) {
    let msg = "Vous avez réussi votre maîtrise ! ";
    
    if (rencontre.name == "Messagers des Rêves") {
      msg += "Le Messager des Rêves vous permet de lancer votre sort à XX cases !";
    
    } else if (rencontre.name == "Passeur des Rêves") {
      msg += "Le Passeur des Rêves vous téléporte sur une case à distance XX !";
      
    } else if (rencontre.name == "Fleur des Rêves") {
      await actor.updatePointsDeReve( rencontre.force );
      msg += "La Fleur des rêves s'évanouit en vous fournissant " + rencontre.force + " Points de Rêve";
      
    } else if (rencontre.name == "Mangeur de Rêve") {
      msg += "Ce Mangeur des Rêves disparait !"
    
    } else if (rencontre.name == "Changeur de Rêve") {
      msg += "Ce Changeur des Rêves disparait !"
      
    } else if (rencontre.name == "Briseur de Rêve") {
      msg += "Ce Briseur des Rêves disparait !"
      
    } else if (rencontre.name == "Reflet d'ancien Rêve") {
      msg += "Ce Reflet d'ancien Rêve disparait !"

    } else if (rencontre.name == "Tourbillon blanc") {
      msg += "Ce Tourbillon Blanc disparait !"

    } else if (rencontre.name == "Tourbillon noir") {
      msg += "Ce Tourbillon Noir disparait !"

    } else if (rencontre.name == "Rêve de Dragon") {
      msg += "Un Rêve de Dragon survient !"
      
    }  
  }
  
  /* -------------------------------------------- */
  static async processRencontreEchec( actor, rencontre ) {
    let msg = "Vous avez échoué à votre maîtrise ! ";
    
    if (rencontre.name == "Messagers des Rêves") {
      msg += "Le Messager des Rêves s'éloigne de vous !";
    
    } else if (rencontre.name == "Passeur des Rêves") {
      msg += "Le Passeur des Rêves s'éloigne de vous !";
      
    } else if (rencontre.name == "Fleur des Rêves") {
      msg += "La Fleur des rêves s'éloigne de vous et se perd dans les Terres Médianes";
      
    } else if (rencontre.name == "Mangeur de Rêve") {
      await actor.updatePointsDeReve( -rencontre.force );
      msg += "Ce Mangeur des Rêves croque votre Rêve ! Vous perdez " + rencontre.force + " points de rêve actuels, votre nouveau total est de " + actor.data.data.reve.reve.value;      
    
    } else if (rencontre.name == "Changeur de Rêve") {
      let coordTMR = actor.data.data.reve.tmrpos.coord;
      let newcoordTMR = this.getRandomLocationType(coordTMR);
      msg += "Vous avez été téléporté en "; // TODO
      
    } else if (rencontre.name == "Briseur de Rêve") {
      msg += "Votre Rêve est Brisé, vous quittez les Terres Médianes";
      
    } else if (rencontre.name == "Reflet d'ancien Rêve") {
      msg += "Votre Rêve est Brisé, vous quittez les Terres Médianes";

    } else if (rencontre.name == "Tourbillon blanc") {
      msg += "Votre Rêve est Brisé, vous quittez les Terres Médianes";

    } else if (rencontre.name == "Tourbillon noir") {
      msg += "Votre Rêve est Brisé, vous quittez les Terres Médianes";

    } else if (rencontre.name == "Rêve de Dragon") {
      
    }
  }
  
  /* -------------------------------------------- */
  static async genericGetTableResult( tableName, toChat)
  {
    let pack = game.packs.get("foundryvtt-reve-de-dragon.tables-diverses");
    await pack.getIndex();
    let entry = pack.index.find(e => e.name === tableName);
    let rollQueues = await pack.getEntity(entry._id);
    let result = rollQueues.draw( { displayChat: toChat } );
    return result;
  }
  
  /* -------------------------------------------- */
  static async getSouffle( toChat ) {
    return TMRUtility.genericGetTableResult( "Souffles de Dragon", toChat);
  }

  /* -------------------------------------------- */
  static async getQueue( toChat = true) {
    return TMRUtility.genericGetTableResult( "Queues de dragon", toChat);
  }

  /* -------------------------------------------- */
  static async getTete( toChat = true ) {
    return TMRUtility.genericGetTableResult( "Têtes de Dragon pour haut-rêvants", toChat);
  }
  
  /* -------------------------------------------- */
  static async getTeteHR( toChat = true ) {
    return TMRUtility.genericGetTableResult( "Têtes de Dragon pour tous personnages", toChat);
  }

  /* -------------------------------------------- */
  static async getOmbre( toChat = true ) {
    return TMRUtility.genericGetTableResult( "Ombre de Thanatos", toChat);
  }
  
  /* -------------------------------------------- */
  /**
   * Retourne une recontre en fonction de la case ou du tirage
   * @param {*} caseName 
   * @param {*} roll 
   */
  static getRencontre( caseName, roll ) {
    if (!roll) {
      roll = new Roll("1d100").roll().total;
    }
    if ( !caseName) {
      ChatMessage.create({ content: "Un nom de case doit être indiqué (ie /tmrr desert ou /tmrr cite)" });
      return false;
    }
    caseName = caseName.toLowerCase();
    caseName = caseName.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
    //console.log("Case : ", caseName);
    for( let renc of rencontresTable) {
      let scoreDef = renc.data[caseName];
      let min = scoreDef.substr(0,2);
      let max = scoreDef.substr(3,2);
      if ( roll >= min && roll <= max) {
        let force = new Roll(renc.data.force).roll().total;
        ChatMessage.create({ content: "Rencontre en " + caseName +  "(jet : " + roll + "%)<br>Vous rencontrez un " + renc.name + " d'une force de " + force + " Points de Rêve" });
        return false;
      }
    }

  }

  /* -------------------------------------------- */
  /**
   * 
   */
  static getTMRAleatoire()
  {
    let num = new Roll("1d15").roll().total;
    let letter, letterValue;
    if ( num == 15) {
      letterValue = new Roll( "1d7").roll().total;
      letter = String.fromCharCode( 65 + ((parseInt(letterValue)-1)*2) );
    } else {
      letterValue = new Roll( "1d13 + 64" ).roll().total;
      letter = String.fromCharCode( letterValue );
    }
    let caseIndex = letter+num;
    console.log("Case ", letterValue, letter, num, TMRMapping[caseIndex].label );
  }
}

