"use strict";

let getOptions = require('./getOptions').default;

let fs = require('fs');

let coverageCollector = require('../jest/coverageCollector');

let path = require('path');

let {
  htmlTemplate,
  endTag
} = require('../templates/linterConstant');

let {
  esLint: {
    srcBranch,
    targetBranch,
    serviceName,
    impactServerDomain,
    impactRun,
    reportType,
    reportPath
  }
} = getOptions();

function writeFile(filePath, data) {
  filePath = path.join(process.cwd(), filePath); //eslint-disable-line

  let dirName = path.dirname(filePath);

  if (!fs.existsSync(dirName)) {
    fs.mkdirSync(dirName);
    fs.writeFileSync(filePath, data);
  } else {
    fs.writeFileSync(filePath, data);
  }
}

let formatter = {
  jsonFormatter: data => {
    let finalList = [];
    data.forEach(errorFileObj => {
      let tempMessageList = [];
      errorFileObj.messages.forEach(messageObj => {
        if (messageObj.ruleId === '@zohodesk/zsecurity/no-protocol-check' || messageObj.ruleId === '@zohodesk/zsecurity/no-unsecure-html') {
          tempMessageList.push(messageObj);
        }
      });

      if (tempMessageList.length > 0) {
        finalList.push(errorFileObj);
      }
    });
    return finalList;
  },
  htmlFormatter: data => {
    data = formatter.jsonFormatter(data); //eslint-disable-line

    if (data.length > 0) {
      let liTag = '';
      data.forEach(errorFileObj => {
        liTag = `${liTag}<li class="pkLi"><div class="pkRow"> <div class="pkArrowCont" onclick="toggleWrapper(this)"> <div class="pkArrow"></div></div><div class="pkFileName">File Name :</div><div class="pkUrl">${errorFileObj.filePath}</div></div><div class="pkDetails"><div class="pkDetailsHead"> <div class="pkDetailsCol">Line No</div><div class="pkDetailsCol">Type</div><div class="pkDetailsCol">Message</div><div class="pkDetailsCol">Name</div></div><div class="pkDetailsBody">`;
        let messageTag = '';
        errorFileObj.messages.forEach(messageObj => {
          let errorType = messageObj.severity == 2 ? 'Error' : 'Warning'; //eslint-disable-line

          messageTag = `${messageTag}<div class="pkDetailsRow"><div class="pkDetailsCol">${messageObj.line}</div><div class="pkDetailsCol pkError">${errorType}</div><div class="pkDetailsCol">${messageObj.message}</div><div class="pkDetailsCol">${messageObj.ruleId}</div></div>`;
        });
        liTag = `${liTag + messageTag}</div></div></li>`;
      });
      return `${htmlTemplate}<ul class="pkUl">${liTag}</ul>${endTag}`;
    }

    return `${htmlTemplate}<div class="pkEmpty"><div>No test results with found</div></div>${endTag}`;
  },
  xmlFormatter: data => {
    data = formatter.jsonFormatter(data); //eslint-disable-line

    let startTag = '<jscheck>';
    let engTag = '</jscheck>';
    let bodyContent = '';
    data.forEach(errorFileObj => {
      let startOfFile = `<file name="${errorFileObj.filePath}">`;
      let endOfFile = '</file>';
      let messageContent = '';
      errorFileObj.messages.forEach(messageObj => {
        messageContent = `${messageContent}<violation fromLine = "${messageObj.line}" type ="${messageObj.ruleId}" message ="${messageObj.message}" ></violation>`;
      });
      bodyContent = bodyContent + startOfFile + messageContent + endOfFile;
    });
    return startTag + bodyContent + engTag;
  }
};

function formatSplitter(inputJson) {
  let outputData;

  if (reportType === 'json') {
    outputData = JSON.stringify(formatter.jsonFormatter(inputJson));
  } else if (reportType === 'html') {
    outputData = formatter.htmlFormatter(inputJson);
  } else if (reportType === 'xml') {
    outputData = formatter.xmlFormatter(inputJson);
  }

  writeFile(reportPath, outputData);
}

module.exports = function (results) {
  let erroredFileObjectList = [];
  results.forEach(fileObject => {
    if (fileObject.errorCount > 0) {
      erroredFileObjectList.push({
        filePath: fileObject.filePath,
        messages: fileObject.messages,
        errorCount: fileObject.errorCount,
        shortPath: fileObject.filePath.split('/supportapp/')[1]
      });
    }
  });

  if (impactRun) {
    coverageCollector(srcBranch, targetBranch, serviceName, impactServerDomain).then((res = {}) => {
      let impactList = [];

      if (res.STATUS) {
        if (res.LIST.length > 0) {
          erroredFileObjectList.forEach(errFileObj => {
            if (res.LIST.indexOf(errFileObj.shortPath) > -1) {
              impactList.push(errFileObj);
            }
          });
          formatSplitter(impactList);
        }
      }
    });
  } else {
    formatSplitter(erroredFileObjectList);
  }
};