/* eslint-disable unicorn/prefer-module */
/*
 * Copyright (C) 2018-2019 StApps
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */
import {expect} from 'chai';
import {unlink} from 'fs/promises';
import {createDiagram, createDiagramFromString} from '../src/index.js';
import {UMLConfig} from '../src/index.js';
import {lightweightDefinitionsFromPath} from '@openstapps/easy-ast';
import nock = require('nock');
import path from 'path';
import {existsSync} from 'fs';
import {fileURLToPath} from 'url';

describe('CreateDiagram', function () {
  this.timeout(15_000);
  this.slow(5000);

  const plantUmlConfig: UMLConfig = {
    definitions: [],
    showAssociations: true,
    showEnumValues: true,
    showInheritance: true,
    showInheritedProperties: true,
    showOptionalProperties: true,
    showProperties: true,
  };

  const definitions = lightweightDefinitionsFromPath('./test/model');

  it('should refuse request', async function () {
    const testPlantUmlCode = 'class Test{\n}';
    try {
      await createDiagramFromString(testPlantUmlCode, 'http://plantuml:8080');
    } catch (error) {
      expect([
        new Error('getaddrinfo ENOTFOUND plantuml plantuml:8080').message,
        new Error('getaddrinfo EAI_AGAIN plantuml plantuml:8080').message,
        new Error('getaddrinfo ENOTFOUND plantuml').message,
      ]).to.include((error as NodeJS.ErrnoException).message);
    }
  });

  /**
   * This test will only test the functionality of the method
   * - Converting the definitions to plantuml code
   * - Sending the code to a server
   * - Writing the response to a file
   * This test will not check the file content
   */
  it('should create diagrams', async function () {
    nock('http://plantuml:8080')
      .persist()
      .get(() => true)
      .reply(200, 'This will be the file content');

    let fileName = await createDiagram(definitions, plantUmlConfig, 'http://plantuml:8080');
    let filePath = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', fileName);
    expect(existsSync(filePath)).to.be.true;

    await unlink(fileName);
    plantUmlConfig.showAssociations = false;

    plantUmlConfig.showInheritance = false;
    fileName = await createDiagram(definitions, plantUmlConfig, 'http://plantuml:8080');
    filePath = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', fileName);
    expect(existsSync(filePath)).to.be.true;
    await unlink(fileName);

    nock.cleanAll();
  });
});
