type Gamma = "A" | "B" | "C" | "D" | "E" | 'F' | "G";

type BaseNote =
  "A" | "B" | "C" | "D" | "E" | 'F' | "G" |
  "Ab" | "Bb" | "Cb" | "Db" | "Eb" | "Fb" | "Gb" |
  "Am" | "Bm" | "Cm" | "Dm" | "Em" | "Fm" | "Gm" |
  "Abm" | "Bbm" | "Cbm" | "Dbm" | "Ebm" | "Fbm" | "Gbm";

function buildGamma(baseNote: Gamma, poluton: string[], isBemol: boolean = false) {
  const gamma = ['C', 'D', 'E', 'F', 'G', 'A', 'B'];
  const gammaIndexNote = gamma.findIndex((n) => n === baseNote);
  const gammaBaseNote = gammaIndexNote !== 0 ? [...gamma.slice(gammaIndexNote), ...gamma.slice(0, gammaIndexNote)] : gamma.slice(gammaIndexNote);

  const resultGamma = gammaBaseNote.map(n => {
    if (poluton.includes(n)) {
      return isBemol ? n + "b" : n + "#";
    }
    return n;
  })

  return resultGamma;
}


export function buildTonalnost(baseNote: BaseNote) {
  let res: string[] = [];
  const searchSeaquencies = ['F', 'C', 'G', 'D', 'A', 'E', 'B'];
  const gamma = ['C', 'D', 'E', 'F', 'G', 'A', 'B'];
  const isMinor = baseNote.slice(-1) === 'm'
  const isBemol = /b/.test(baseNote);
  const isDies = !isBemol;
  const note = baseNote.slice(0, 1);

  if (isDies) {
    const gammaIndexNote = gamma.findIndex((n) => n === note);
    const prevNoteGammIndex = gammaIndexNote === 0 ? 6 : gammaIndexNote - 1;
    const noteSearchSeq = gamma[prevNoteGammIndex];
    const searchSeaquenciesIndex = searchSeaquencies.findIndex(n => n === noteSearchSeq);
    const diesSlice = searchSeaquencies.slice(0, searchSeaquenciesIndex + 1)
    res = buildGamma(note as Gamma, diesSlice)
  }

  if (isBemol) {
    const searchSeaquenciesIndex = searchSeaquencies.findIndex(n => n === note);
    const prevNoteSearchSeqIndex = searchSeaquenciesIndex === 0 ? 6 : searchSeaquenciesIndex - 1;
    const bemoleSlice = searchSeaquencies.slice(prevNoteSearchSeqIndex);
    res = buildGamma(note as Gamma, bemoleSlice, true)
  }

  if (isMinor) {
    console.log({ isMinor })
  }

  return res.join(' | ');
};
