import { SinglePlaylistType } from '../../contexts/PlaylistContext/PlaylistContext';
// const XMLParser = require('react-xml-parser');
import XMLParser from '../../xml';

const fs = require('fs');

const fileExist = (path: string): Promise<boolean> => {
  return new Promise( r => {
    fs.access(path, fs.F_OK, (err: any) => {
      if (err) {
        r(false);
      }
      r(true);
    });
  });
};

export const selectSingleFiles = (playlistData: SinglePlaylistType[]): string[] => {
  const singleFiles: string[] = [];
  for(const row of playlistData) {
    for(const grid of row.grid) {
      if (!grid) continue;
      if (singleFiles.indexOf(grid.filePath) >= 0) {
        continue;
      }
      singleFiles.push(grid.filePath);
    }
  }
  return singleFiles;
}

export const retreivePlaylistFile = (filePath: string, config: {rows: number, columns: number}): Promise<SinglePlaylistType[]> => {
  return new Promise((resolve) => {
    console.log('before readFile');
    fs.readFile(filePath, 'utf-8', async (err: any, data: any) => {
      console.log('after readFile');
      const xml = new XMLParser().parseFromString(data);
      const pages = xml.children[3].children;
      const path = filePath.split('\\');
      path.splice(-1, 1); // .join('\\');
      const pathFolder = path.join('\\');
      const output = [];
      for (let i = 0; i < pages.length; i += 1) {
        const page = pages[i];
        const moduleList = page.children[1].children;
        const grid: any = [];
        let error = false;
        for (const module of moduleList) {
          // const source = module.children[0].value;
          let sourcePath = `${pathFolder}\\${module.children[0].value.replace(pathFolder, '')}`;
          let isLive = false;
          let sourceSplit: any[] = [];
          if (module.children[0].value.indexOf('http:\/\/') !== -1 || module.children[0].value.indexOf('https:\/\/') !== -1) {
            isLive = true;
            sourceSplit = sourcePath.split('|');
            //sourcePath = `${pathFolder}\\${module.children[0].value}`;
          }
          const row = Math.floor(module.children[1].value);
          const col = module.children[2].value;
          const gridRow = config.columns * row + parseInt(col);
          const numberOfCells = parseInt(module.children[3].value);
          const isFileExist = await fileExist(isLive ? `${sourceSplit[0]}` : sourcePath);
          if (!isFileExist) error = true;

          grid[gridRow] = {
            filePath: sourcePath,
            width: numberOfCells,
            height: 0,
            duration: parseInt(module.children[4].value),
            row,
            col,
            fileError: error,
          };
        }
        output.push({
          id: `item-${i + 1}`,
          name: page.children[2].value,
          duration: parseInt(page.children[3].value),
          play: !error,
          currentTime: 0,
          sumTime: 0,
          grid,
          error,
        });
      }
      resolve(output);
    });
  });
}