"use strict";

var _path = _interopRequireDefault(require("path"));

var _postcss = _interopRequireDefault(require("postcss"));

var _classHandling = require("../../lib/plugins/utils/classHandling");

var _fileHandling = require("../plugins/utils/fileHandling");

var _utils = require("../utils");

var _ignore = _interopRequireDefault(require("ignore"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

const supportedProps = ['margin-top', 'margin-bottom', 'margin-left', 'margin-right', 'margin', 'padding-top', 'padding-bottom', 'padding-left', 'padding-right', 'padding', 'top', 'bottom', 'left', 'right', 'height', 'width', 'min-height', 'min-width', 'max-height', 'max-width', 'float', 'overflow', 'position', 'display', 'text-align', 'white-space', 'visibility'];
const renameProps = {
  position: {
    cls: 'posn'
  },
  display: {
    cls: 'disp'
  },
  float: {
    cls: 'flo'
  },
  overflow: {
    cls: 'over'
  },
  'text-align': {
    cls: 'txtAlgn'
  },
  'white-space': {
    cls: 'whSpc'
  },
  visibility: {
    cls: 'vis'
  },
  'font-size': {
    pos: 'fs',
    neg: 'fs_'
  },
  'margin-top': {
    pos: 'mt',
    neg: 'mt_'
  },
  'margin-bottom': {
    pos: 'mb',
    neg: 'mb_'
  },
  'margin-left': {
    pos: 'ml',
    neg: 'ml_'
  },
  'margin-right': {
    pos: 'mr',
    neg: 'mr_'
  },
  margin: {
    pos: 'm',
    neg: 'm_'
  },
  'padding-top': {
    pos: 'pt',
    neg: 'pt_'
  },
  'padding-bottom': {
    pos: 'pb',
    neg: 'pb_'
  },
  'padding-left': {
    pos: 'pl',
    neg: 'pl_'
  },
  'padding-right': {
    pos: 'pr',
    neg: 'pr_'
  },
  padding: {
    pos: 'p',
    neg: 'p_'
  },
  top: {
    pos: 'post',
    neg: 'post_'
  },
  bottom: {
    pos: 'posb',
    neg: 'posb_'
  },
  left: {
    pos: 'posl',
    neg: 'posl_'
  },
  right: {
    pos: 'posr',
    neg: 'posr_'
  },
  height: {
    pos: 'h',
    neg: 'h_'
  },
  width: {
    pos: 'w',
    neg: 'w_'
  },
  'min-height': {
    pos: 'minh',
    neg: 'minh_'
  },
  'min-width': {
    pos: 'minw',
    neg: 'minw_'
  },
  'max-height': {
    pos: 'maxh',
    neg: 'maxh_'
  },
  'max-width': {
    pos: 'maxw',
    neg: 'maxw_'
  }
};

function objToClassName(prop, data) {
  return renameProps[prop] ? data < 0 ? renameProps[prop].neg ? `${renameProps[prop].neg}${data * -1}` : `undef${data * -1}` : renameProps[prop].pos ? `${renameProps[prop].pos}${data}` : `undef${data}` : `undef${data}`;
}

function objtoClassNameString(prop, data) {
  let temp = data.toString().replace(/-/gi, '');
  return `${renameProps[prop].cls}_${temp.replace(/\s*/gi, '')}`;
}

const multipleClassName = {
  margin: ['margin-top', 'margin-right', 'margin-bottom', 'margin-left'],
  padding: ['padding-top', 'padding-right', 'padding-bottom', 'padding-left']
};

function objToClassNameMultiple(prop, data) {
  data = data.trim().replace(/\s+/gi, ' ');
  let dataArr = data.split(' ');

  if (dataArr.length === 3) {
    dataArr[3] = dataArr[1];
  }

  if (dataArr.length === 2) {
    dataArr[3] = dataArr[1];
    dataArr[2] = dataArr[0];
  }

  if (dataArr.length === 1) {
    dataArr[3] = dataArr[0];
    dataArr[2] = dataArr[0];
    dataArr[1] = dataArr[0];
  }

  let composeClasses = '';
  dataArr.forEach((data, index) => composeClasses += `${objToClassName(multipleClassName[prop][index], parseInt(data, 10))} `);
  composeClasses = composeClasses.substring(0, composeClasses.length - 1);
  return composeClasses;
}

const commonFilePath = {
  margin: 'src/common/css/margin.css',
  'margin-left': 'src/common/css/margin.css',
  'margin-right': 'src/common/css/margin.css',
  'margin-top': 'src/common/css/margin.css',
  'margin-bottom': 'src/common/css/margin.css',
  padding: 'src/common/css/padding.css',
  'padding-left': 'src/common/css/padding.css',
  'padding-right': 'src/common/css/padding.css',
  'padding-top': 'src/common/css/padding.css',
  'padding-bottom': 'src/common/css/padding.css',
  top: 'src/common/css/position.css',
  bottom: 'src/common/css/position.css',
  left: 'src/common/css/position.css',
  right: 'src/common/css/position.css',
  height: 'src/common/css/height.css',
  width: 'src/common/css/width.css',
  'min-height': 'src/common/css/height.css',
  'min-width': 'src/common/css/width.css',
  'max-height': 'src/common/css/height.css',
  'max-width': 'src/common/css/width.css',
  fontSize: 'src/common/css/fontSize.css',
  textProps: 'src/common/css/textProps.css',
  display: 'src/common/css/textProps.css',
  float: 'src/common/css/textProps.css',
  overflow: 'src/common/css/textProps.css',
  position: 'src/common/css/position.css',
  'text-align': 'src/common/css/textProps.css',
  'white-space': 'src/common/css/textProps.css',
  visibility: 'src/common/css/textProps.css'
};

function generateComposeString(resourcePath, prop, value) {
  let composeString = `from "${_path.default.relative(_path.default.parse(resourcePath).dir, // resourcePath
  commonFilePath[prop]).replace(/\\/gi, '/')}"`;
  let cls = '';

  if (/^position|^overflow|^display|^float|^text-align|^white-space|^visibility/gi.test(prop)) {
    console.log(prop, value, 'textvals');
    cls = objtoClassNameString(prop, value);
  } else if (/^margin$|^padding$/gi.test(prop)) {
    // console.log(prop, value, 'margin');
    cls = objToClassNameMultiple(prop, value);
  } else {
    // console.log(prop, value, 'common');
    cls = objToClassName(prop, parseInt(value));
  }

  composeString = `${cls} ${composeString}`;
  return composeString;
} // const preNames = {
//   height: 'zd-height-',
//   'max-height': 'zd-height-',
//   'min-height': 'zd-height-',
//   width: 'zd-width-',
//   'max-width': 'zd-width-',
//   'min-width': 'zd-width-',
//   top: 'zd-position-',
//   bottom: 'zd-position-',
//   left: 'zd-position-',
//   right: 'zd-position-',
//   'padding-top': 'zd-padding-',
//   'padding-bottom': 'zd-padding-',
//   'padding-left': 'zd-padding-',
//   'padding-right': 'zd-padding-',
//   'margin-top': 'zd-margin-',
//   'margin-bottom': 'zd-margin-',
//   'margin-left': 'zd-margin-',
//   'margin-right': 'zd-margin-'
// };


function allowParent(rule) {
  return rule.parent.type === 'root' || rule.parent.type === 'atrule' && rule.parent.name === 'media';
}

module.exports = function (source) {
  const {
    resourcePath
  } = this;
  const options = (0, _utils.getOptions)(); // console.log(options.app.patterns.composeMinification);
  // const ig = ignore({ allowRelativePaths: true }).add(options.app.patterns.composeMinification);
  // const newFilename = path.relative(path.parse(process.cwd()).base, resourcePath);
  // console.log(newFilename, ig.ignores(newFilename));

  let root = _postcss.default.parse(source);

  if (!(0, _fileHandling.isFileNameMatchingPluginPattern)({
    filename: resourcePath,
    filterArr: options.app.patterns.composeMinification
  })) {
    return root.toString();
  }

  root.walkRules(rule => {
    rule.walkDecls(decl => {
      if (/^-ms|^-webkit|^moz/gi.test(decl.prop)) {
        return;
      }

      if (!allowParent(rule)) {
        return;
      }

      if ((0, _classHandling.isInsideMediaQuery)(rule)) {
        console.log('inside media query', rule.selector);
        return;
      }

      if (supportedProps.includes(decl.prop) && /^position$|^overflow|^float|^display|^text-align|^white-space|^visibility/gi.test(decl.prop) && !/[,\s+]+|(\w+)\.|:|::|body|(\d+)%|>/gi.test(rule.selector) && commonFilePath[decl.prop] && !decl.value.includes('var(--')) {
        decl.value = generateComposeString(resourcePath, decl.prop, decl.value);
        decl.prop = 'composes';
        return;
      }

      if (supportedProps.includes(decl.prop) && /px$/gi.test(decl.value) && !/^--/gi.test(decl.prop) && commonFilePath[decl.prop] && !decl.value.includes('calc') && !/[,\s+]+|(\w+)\.|:|(\d+)%/gi.test(rule.selector)) {
        // n++ < 10 && console.log(composeString);
        // if (!composeString.includes('src')) {
        // if (/px$/gi.test(decl.value)) {
        decl.value = generateComposeString(resourcePath, decl.prop, decl.value); // }
        // if (/^position$|^display$|^overflow$|^float$/gi.test(decl.prop)) {
        //   console.log(decl.prop);
        // }

        decl.prop = 'composes'; // console.log(decl.prop, decl.value);
        // n < 10 && console.log(rule.selector, decl.prop, decl.value);
        // }
      }
    });
  });
  const output = root.toString(); // console.log(output);

  return output;
};