/**
 * Created by cgarcia on 07/01/2019.
 */

function serializeLnbLocOsc(header) {
  var res = '';
  res += '<LNB-LOC-OSC>\n';
  if (header.xml_satellite_band == 'kuka') {
    res += '<BAND_KUKA high="' + header.xml_lnb_high_osc + '" low="' + header.xml_lnb_low_osc + '" units="MHz"/>\n';
  } else {
    res += '<BAND_C value="' + header.xml_lnb_local_osc + '" units="MHz"/>\n';
  }
  res += '</LNB-LOC-OSC>\n';
  return res;
}

function serializeLnb(xml_lnb) {
  var res = '';
  res += '<LNB>' + xml_lnb + '</LNB>\n';
  return res;
}

function serializeTvSystem(xml_stardand_tv) {
  var res = xml_stardand_tv.split('-');
  var system = res[0];
  var standard = res[1];
  var res = '';
  res += '<TV system="' + system.toUpperCase() + '" standard="' + standard.toUpperCase() + '"/>\n';
  return res;
}

function serializeHeader(channelPlan) {
  var res = '';

  if (channelPlan.xml_band == 'satellite') {
    res += '<HEADER>\n';
    if (channelPlan.header.xml_band != '' && channelPlan.header.xml_stardand_tv != undefined) {
      res += serializeLnbLocOsc(channelPlan.header);
    }

    if (channelPlan.header.xml_lnb != '' && channelPlan.header.xml_lnb != 'undefined' && channelPlan.header.xml_lnb != undefined) {
      res += serializeLnb(channelPlan.header.xml_lnb);
    }
    res += '</HEADER>\n';
  } else {
    if (
      (channelPlan.header.xml_stardand_tv != '' && channelPlan.header.xml_stardand_tv != undefined) ||
      (channelPlan.header.xml_lnb != '' && channelPlan.header.xml_lnb != undefined)
    ) {
      res += '<HEADER>\n';
      if (channelPlan.header.xml_stardand_tv != '') {
        res += serializeTvSystem(channelPlan.header.xml_stardand_tv);
      }
      if (channelPlan.header.xml_lnb != '' && channelPlan.header.xml_lnb != 'undefined' && channelPlan.header.xml_lnb != undefined) {
        res += serializeLnb(channelPlan.header.xml_lnb);
      }
      res += '</HEADER>\n';
    } else {
      res += '<HEADER />\n';
    }
  }

  return res;
}

function serializeExtra(channelPlan) {
  var res = '';

  if (channelPlan.xml_band == 'terrestrial') {
    if (channelPlan.header.xml_startBandFreq == undefined || channelPlan.header.xml_startBandFreq == '') {
      channelPlan.header.xml_startBandFreq = 5;
    }
    if (channelPlan.header.xml_stopBandFreq == undefined || channelPlan.header.xml_stopBandFreq == '') {
      channelPlan.header.xml_stopBandFreq = 1000;
    }
    if (channelPlan.header.xml_avg_filter == undefined || channelPlan.header.xml_avg_filter == '') {
      channelPlan.header.xml_avg_filter = 0;
    }
    if (channelPlan.header.xml_video_filter == undefined || channelPlan.header.xml_video_filter == '') {
      channelPlan.header.xml_video_filter = 16;
    }

    if (
      channelPlan.header.xml_startBandFreq != 5 ||
      channelPlan.header.xml_stopBandFreq != 1000 ||
      channelPlan.header.xml_avg_filter != 0 ||
      channelPlan.header.xml_video_filter != 16
    ) {
      res += '<EXTRA>\n';
      res += '<SP>\n';
      res += '<STARTBANDFREQ frequency="' + channelPlan.header.xml_startBandFreq + '" units="MHz"/>\n';
      res += '<STOPBANDFREQ frequency="' + channelPlan.header.xml_stopBandFreq + '" units="MHz"/>\n';
      res += '<AVGFILTER value="' + channelPlan.header.xml_avg_filter + '" />\n';
      res += '<VIDEOFILTER value="' + channelPlan.header.xml_video_filter + '" />\n';
      res += '</SP>\n';
      res += '</EXTRA>\n';
    }
  } else {
    if (channelPlan.header.xml_startBandFreq == undefined || channelPlan.header.xml_startBandFreq == '') {
      channelPlan.header.xml_startBandFreq = 250;
    }
    if (channelPlan.header.xml_stopBandFreq == undefined || channelPlan.header.xml_stopBandFreq == '') {
      channelPlan.header.xml_stopBandFreq = 2500;
    }
    if (channelPlan.header.xml_avg_filter == undefined || channelPlan.header.xml_avg_filter == '') {
      channelPlan.header.xml_avg_filter = 0;
    }
    if (channelPlan.header.xml_video_filter == undefined || channelPlan.header.xml_video_filter == '') {
      channelPlan.header.xml_video_filter = 16;
    }

    if (
      channelPlan.header.xml_startBandFreq != 250 ||
      channelPlan.header.xml_stopBandFreq != 2500 ||
      channelPlan.header.xml_avg_filter != 0 ||
      channelPlan.header.xml_video_filter != 16
    ) {
      res += '<EXTRA>\n';
      res += '<SP>\n';
      res += '<STARTBANDFREQ frequency="' + channelPlan.header.xml_startBandFreq + '" units="MHz"/>\n';
      res += '<STOPBANDFREQ frequency="' + channelPlan.header.xml_stopBandFreq + '" units="MHz"/>\n';
      res += '<AVGFILTER value="' + channelPlan.header.xml_avg_filter + '" />\n';
      res += '<VIDEOFILTER value="' + channelPlan.header.xml_video_filter + '" />\n';
      res += '</SP>\n';
      res += '</EXTRA>\n';
    }
  }

  return res;
}

function serializeJSONHeader(jsonObj, xmlDoc) {
  var foundedSatBand = false;
  jsonObj.header = {};

  for (var i = 0; i < xmlDoc.getElementsByTagName('HEADER')[0].childNodes.length; i++) {
    switch (xmlDoc.getElementsByTagName('HEADER')[0].childNodes[i].nodeName) {
      case 'TV':
        jsonObj.header.xml_stardand_tv =
          xmlDoc.getElementsByTagName('HEADER')[0].childNodes[i].getAttribute('system').toLowerCase() +
          '-' +
          xmlDoc.getElementsByTagName('HEADER')[0].childNodes[i].getAttribute('standard').toLowerCase();
        break;
      case 'LNB':
        jsonObj.header.xml_lnb = xmlDoc.getElementsByTagName('HEADER')[0].childNodes[i].innerHTML;
        break;
      case 'LNB-LOC-OSC':
        foundedSatBand = true;
        for (var j = 0; j < xmlDoc.getElementsByTagName('HEADER')[0].childNodes[i].childNodes.length; j++) {
          switch (xmlDoc.getElementsByTagName('HEADER')[0].childNodes[i].childNodes[j].nodeName) {
            case 'BAND_KUKA':
              jsonObj.header.xml_stardand_tv = '';
              jsonObj.header.xml_satellite_band = 'kuka';
              jsonObj.header.xml_lnb_low_osc = xmlDoc.getElementsByTagName('HEADER')[0].childNodes[i].childNodes[j].getAttribute('low');
              jsonObj.header.xml_lnb_high_osc = xmlDoc.getElementsByTagName('HEADER')[0].childNodes[i].childNodes[j].getAttribute('high');
              jsonObj.header.xml_lnb_local_osc = '';
              break;
            case 'BAND_C':
              jsonObj.header.xml_stardand_tv = '';
              jsonObj.header.xml_satellite_band = 'c';
              jsonObj.header.xml_lnb_local_osc = xmlDoc.getElementsByTagName('HEADER')[0].childNodes[i].childNodes[j].getAttribute('value');
              jsonObj.header.xml_lnb_low_osc = '';
              jsonObj.header.xml_lnb_high_osc = '';
              break;
          }
        }
        break;
    }

    if (!foundedSatBand) {
      jsonObj.header.xml_satellite_band = '';
      jsonObj.header.xml_lnb_local_osc = '';
      jsonObj.header.xml_lnb_low_osc = '';
      jsonObj.header.xml_lnb_high_osc = '';
    }
  }

  if (xmlDoc.getElementsByTagName('EXTRA')[0] != undefined) {
    for (var i = 0; i < xmlDoc.getElementsByTagName('EXTRA')[0].childNodes.length; i++) {
      if (xmlDoc.getElementsByTagName('EXTRA')[0].childNodes[i].nodeName == 'SP') {
        for (var j = 0; j < xmlDoc.getElementsByTagName('EXTRA')[0].childNodes[i].childNodes.length; j++) {
          switch (xmlDoc.getElementsByTagName('EXTRA')[0].childNodes[i].childNodes[j].nodeName) {
            case 'STARTBANDFREQ':
              jsonObj.header.xml_startBandFreq = xmlDoc.getElementsByTagName('EXTRA')[0].childNodes[i].childNodes[j].getAttribute('frequency');
              break;
            case 'STOPBANDFREQ':
              jsonObj.header.xml_stopBandFreq = xmlDoc.getElementsByTagName('EXTRA')[0].childNodes[i].childNodes[j].getAttribute('frequency');
              break;
            case 'AVGFILTER':
              jsonObj.header.xml_avg_filter = xmlDoc.getElementsByTagName('EXTRA')[0].childNodes[i].childNodes[j].getAttribute('value');
              break;
            case 'VIDEOFILTER':
              jsonObj.header.xml_video_filter = xmlDoc.getElementsByTagName('EXTRA')[0].childNodes[i].childNodes[j].getAttribute('value');
              break;
          }
        }
      }

      if (!foundedSatBand) {
        jsonObj.header.xml_satellite_band = '';
        jsonObj.header.xml_lnb_local_osc = '';
        jsonObj.header.xml_lnb_low_osc = '';
        jsonObj.header.xml_lnb_high_osc = '';
      }
    }
  }
}

function serializeJSONChannels(jsonObj, xmlDoc, family_equipment) {
  var tmpChannelObj = {};

  jsonObj.descendantsNodeNames = ['CHANNELS'];
  jsonObj.channels = [];
  jsonObj.arrayDBG = [[], [], [], [], [], [], [], [], [], []];

  if (family_equipment == 'D0') {
    //Remove #text element from the DOM
    for (var i = 0; i < xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes.length; i++) {
      if (
        xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].nodeName == '#text' ||
        xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].nodeName == '#comment'
      ) {
        xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].remove();
        i--;
      }
    }

    for (var i = 0; i < xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes.length; i++) {
      console.log('channel: ' + i);
      tmpChannelObj.xml_channel_name = xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].getAttribute('name');

      if (jsonObj.xml_band == 'terrestrial') {
        tmpChannelObj.xml_channel_frequency = xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].getAttribute('frequency');
      } else {
        tmpChannelObj.xml_channel_frequency = xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].getAttribute('downlink');
      }

      if (xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].childNodes.length > 0) {
        //Remove #text element from the DOM
        for (var j = 0; j < xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].childNodes.length; j++) {
          if (
            xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].childNodes[j].nodeName == '#text' ||
            xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].childNodes[j].nodeName == '#comment'
          ) {
            xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].childNodes[j].remove();
            j--;
          }
        }

        for (var j = 0; j < xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].childNodes.length; j++) {
          if (xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].childNodes[j].nodeName == 'SIGNAL') {
            //Remove #text element from the DOM
            for (var k = 0; k < xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].childNodes[j].childNodes.length; k++) {
              if (
                xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].childNodes[j].childNodes[k].nodeName == '#text' ||
                xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].childNodes[j].childNodes[k].nodeName == '#comment'
              ) {
                xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].childNodes[j].childNodes[k].remove();
                k--;
              }
            }

            for (var k = 0; k < xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].childNodes[j].childNodes.length; k++) {
              if (
                xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].childNodes[j].childNodes[k].nodeName == 'ANALOGTER' ||
                xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].childNodes[j].childNodes[k].nodeName == 'ANALOGSAT'
              ) {
                tmpChannelObj.xml_signalType = 'analog';
              } else {
                tmpChannelObj.xml_signalType = xmlDoc
                  .getElementsByTagName('CHANNELS')[0]
                  .childNodes[i].childNodes[j].childNodes[k].nodeName.toLowerCase();
              }

              if (xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].childNodes[j].childNodes.length > 0) {
                //Remove #text element from the DOM
                for (var l = 0; l < xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].childNodes[j].childNodes[k].childNodes.length; l++) {
                  if (
                    xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].childNodes[j].childNodes[k].childNodes[l].nodeName == '#text' ||
                    xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].childNodes[j].childNodes[k].childNodes[l].nodeName == '#comment'
                  ) {
                    xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].childNodes[j].childNodes[k].childNodes[l].remove();
                    l--;
                  }
                }

                for (var l = 0; l < xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].childNodes[j].childNodes[k].childNodes.length; l++) {
                  tmpChannelObj.expanded = true;
                  switch (xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].childNodes[j].childNodes[k].childNodes[l].nodeName) {
                    case 'BANDWIDTH':
                      tmpChannelObj.xml_channel_bandwidth = xmlDoc
                        .getElementsByTagName('CHANNELS')[0]
                        .childNodes[i].childNodes[j].childNodes[k].childNodes[l].getAttribute('value');
                      break;
                    case 'TV':
                      tmpChannelObj.xml_channel_stardand_tv =
                        xmlDoc
                          .getElementsByTagName('CHANNELS')[0]
                          .childNodes[i].childNodes[j].childNodes[k].childNodes[l].getAttribute('system')
                          .toLowerCase() +
                        '-' +
                        xmlDoc
                          .getElementsByTagName('CHANNELS')[0]
                          .childNodes[i].childNodes[j].childNodes[k].childNodes[l].getAttribute('standard')
                          .toLowerCase();
                      break;
                    case 'PROFILE':
                      if (!tmpChannelObj.hasOwnProperty('children')) {
                        tmpChannelObj.children = [];
                      }
                      tmpChannelObj.children.push({
                        profile: xmlDoc
                          .getElementsByTagName('CHANNELS')[0]
                          .childNodes[i].childNodes[j].childNodes[k].childNodes[l].getAttribute('value')
                          .toLowerCase(),
                        expanded: true,
                        children: [],
                      });

                      break;
                    case 'SYMBOLRATE':
                      if (!tmpChannelObj.hasOwnProperty('children')) {
                        tmpChannelObj.children = [{}];
                      }

                      tmpChannelObj.children[0].xml_channel_symbol_rate = xmlDoc
                        .getElementsByTagName('CHANNELS')[0]
                        .childNodes[i].childNodes[j].childNodes[k].childNodes[l].getAttribute('value');
                      break;
                    case 'LAYER':
                      if (!tmpChannelObj.hasOwnProperty('children')) {
                        tmpChannelObj.children = [];
                      }
                      tmpChannelObj.children.push({
                        layer: xmlDoc
                          .getElementsByTagName('CHANNELS')[0]
                          .childNodes[i].childNodes[j].childNodes[k].childNodes[l].getAttribute('value')
                          .toLowerCase(),
                      });
                      break;

                    default:
                      break;
                  }
                }

                for (var l = 0; l < xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].childNodes[j].childNodes[k].childNodes.length; l++) {
                  switch (xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].childNodes[j].childNodes[k].childNodes[l].nodeName) {
                    case 'PROFILE':
                      //Remove #text element from the DOM
                      for (
                        var m = 0;
                        m < xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].childNodes[j].childNodes[k].childNodes[l].childNodes.length;
                        m++
                      ) {
                        if (
                          xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].childNodes[j].childNodes[k].childNodes[l].childNodes[m].nodeName ==
                            '#text' ||
                          xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].childNodes[j].childNodes[k].childNodes[l].childNodes[m].nodeName ==
                            '#comment'
                        ) {
                          xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].childNodes[j].childNodes[k].childNodes[l].childNodes[m].remove();
                          m--;
                        }
                      }

                      for (
                        var m = 0;
                        m < xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].childNodes[j].childNodes[k].childNodes[l].childNodes.length;
                        m++
                      ) {
                        tmpChannelObj.children[l].children.push({
                          xml_plp_value: xmlDoc
                            .getElementsByTagName('CHANNELS')[0]
                            .childNodes[i].childNodes[j].childNodes[k].childNodes[l].childNodes[m].getAttribute('value'),
                        });
                      }
                      break;
                  }
                }
              }
            }
          }
          if (jsonObj.xml_band == 'satellite') {
            if (xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].childNodes[j].nodeName == 'SAT') {
              if (!tmpChannelObj.hasOwnProperty('children')) {
                tmpChannelObj.children = [{}];
                tmpChannelObj.expanded = true;
              }
              tmpChannelObj.children[0].xml_channel_band = xmlDoc
                .getElementsByTagName('CHANNELS')[0]
                .childNodes[i].childNodes[j].getAttribute('band')
                .toLowerCase();
              tmpChannelObj.children[0].xml_channel_polarization = xmlDoc
                .getElementsByTagName('CHANNELS')[0]
                .childNodes[i].childNodes[j].getAttribute('polarization')
                .toLowerCase();
              tmpChannelObj.children[0].xml_channel_lnb = '';
              tmpChannelObj.children[0].checkLNB = false;
            } else if (xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].childNodes[j].nodeName == 'LNB') {
              if (!tmpChannelObj.hasOwnProperty('children')) {
                tmpChannelObj.children = [{}];
                tmpChannelObj.expanded = true;
              }

              tmpChannelObj.children[0].xml_channel_band = '';
              tmpChannelObj.children[0].xml_channel_polarization = '';
              tmpChannelObj.children[0].xml_channel_lnb = xmlDoc.getElementsByTagName('CHANNELS')[0].childNodes[i].childNodes[j].innerHTML;
              tmpChannelObj.children[0].checkLNB = true;
            } else {
              if (!tmpChannelObj.hasOwnProperty('children')) {
                tmpChannelObj.children = [];
                tmpChannelObj.expanded = true;
                tmpChannelObj.children.push({
                  xml_channel_band: '',
                  xml_channel_polarization: '',
                  checkLNB: false,
                  xml_channel_lnb: '',
                });
              }
            }
          }
        }
      } else {
        tmpChannelObj.xml_signalType = '';
      }

      jsonObj.channels.push(tmpChannelObj);
      tmpChannelObj = {};
    }

    jsonObj.channels.sort(function (a, b) {
      return parseFloat(a.xml_channel_frequency) > parseFloat(b.xml_channel_frequency)
        ? 1
        : parseFloat(b.xml_channel_frequency) > parseFloat(a.xml_channel_frequency)
          ? -1
          : 0;
    });
  } else {
    //Remove #text element from the DOM
    for (var i = 0; i < xmlDoc.getElementsByTagName('CHANNEL_PLAN')[0].childNodes.length; i++) {
      if (
        xmlDoc.getElementsByTagName('CHANNEL_PLAN')[0].childNodes[i].nodeName == '#text' ||
        xmlDoc.getElementsByTagName('CHANNEL_PLAN')[0].childNodes[i].nodeName == '#comment'
      ) {
        xmlDoc.getElementsByTagName('CHANNEL_PLAN')[0].childNodes[i].remove();
        i--;
      }
    }

    for (var i = 0; i < xmlDoc.getElementsByTagName('CHANNEL_PLAN')[0].childNodes.length; i++) {
      tmpChannelObj.xml_channel_name = xmlDoc.getElementsByTagName('CHANNEL_PLAN')[0].childNodes[i].getAttribute('name');
      tmpChannelObj.xml_standard = xmlDoc.getElementsByTagName('CHANNEL_PLAN')[0].childNodes[i].getAttribute('standard');
      tmpChannelObj.expanded = true;
      tmpChannelObj.children = [];
      var tmpChildrenObj = {};

      //Remove #text element from the DOM
      for (var j = 0; j < xmlDoc.getElementsByTagName('CHANNEL_PLAN')[0].childNodes[i].childNodes.length; j++) {
        if (
          xmlDoc.getElementsByTagName('CHANNEL_PLAN')[0].childNodes[i].childNodes[j].nodeName == '#text' ||
          xmlDoc.getElementsByTagName('CHANNEL_PLAN')[0].childNodes[i].childNodes[j].nodeName == '#comment'
        ) {
          xmlDoc.getElementsByTagName('CHANNEL_PLAN')[0].childNodes[i].childNodes[j].remove();
          j--;
        }
      }

      for (var j = 0; j < xmlDoc.getElementsByTagName('CHANNEL_PLAN')[0].childNodes[i].childNodes.length; j++) {
        //without modifications
        var pureBandwith;
        var pureFreq;

        switch (xmlDoc.getElementsByTagName('CHANNEL_PLAN')[0].childNodes[i].childNodes[j].nodeName) {
          case 'active':
            tmpChannelObj.xml_active = xmlDoc.getElementsByTagName('CHANNEL_PLAN')[0].childNodes[i].childNodes[j].innerHTML;
            break;
          case 'bandwidth':
            pureBandwith = xmlDoc.getElementsByTagName('CHANNEL_PLAN')[0].childNodes[i].childNodes[j].innerHTML;
            tmpChannelObj.xml_bandwidth = (
              parseFloat(xmlDoc.getElementsByTagName('CHANNEL_PLAN')[0].childNodes[i].childNodes[j].innerHTML) / 1000000
            ).toFixed(2);
            break;
          case 'docsisGroup':
            var docsisHTML = xmlDoc.getElementsByTagName('CHANNEL_PLAN')[0].childNodes[i].childNodes[j].innerHTML;
            if (docsisHTML != '' && docsisHTML != '--' && docsisHTML != 'undefined' && docsisHTML != undefined) {
              tmpChildrenObj.xml_docsis_group = xmlDoc.getElementsByTagName('CHANNEL_PLAN')[0].childNodes[i].childNodes[j].innerHTML;
              jsonObj.arrayDBG[tmpChildrenObj.xml_docsis_group].push(tmpChildrenObj.xml_docsis_group);
            }
            break;
          case 'freqAudio':
            tmpChildrenObj.xml_freq_audio = xmlDoc.getElementsByTagName('CHANNEL_PLAN')[0].childNodes[i].childNodes[j].innerHTML;
            break;
          case 'frequency':
            tmpChannelObj.xml_channel_frequency = (
              parseFloat(xmlDoc.getElementsByTagName('CHANNEL_PLAN')[0].childNodes[i].childNodes[j].innerHTML) / 1000000
            ).toFixed(2);
            pureFreq = xmlDoc.getElementsByTagName('CHANNEL_PLAN')[0].childNodes[i].childNodes[j].innerHTML;
            break;
          case 'frequencyOffset':
            tmpChildrenObj.xml_frequency_offset = (
              parseFloat(xmlDoc.getElementsByTagName('CHANNEL_PLAN')[0].childNodes[i].childNodes[j].innerHTML) / 1000000
            ).toFixed(2);
            break;
          case 'primaryCarrier':
            tmpChildrenObj.xml_primary_carrier = xmlDoc.getElementsByTagName('CHANNEL_PLAN')[0].childNodes[i].childNodes[j].innerHTML;
            break;
          case 'system':
            tmpChannelObj.xml_signalType = xmlDoc.getElementsByTagName('CHANNEL_PLAN')[0].childNodes[i].childNodes[j].innerHTML;
            break;
          case 'type':
            tmpChannelObj.xml_channel_type = xmlDoc.getElementsByTagName('CHANNEL_PLAN')[0].childNodes[i].childNodes[j].innerHTML;
            if (tmpChannelObj.xml_channel_type == 'ANALOG') {
              tmpChannelObj.xml_channel_frequency = calcularFrecAnalogica(pureFreq, pureBandwith) / 1000000;
              // tmpChannelObj.xml_channel_frequency=tmpChannelObj.xml_channel_frequency - (tmpChannelObj.xml_bandwidth/2)+1.25;
            }

            break;
        }
      }
      tmpChannelObj.children.push(tmpChildrenObj);
      jsonObj.channels.push(tmpChannelObj);
      tmpChildrenObj = {};
      tmpChannelObj = {};
    }
    jsonObj.channels.sort(function (a, b) {
      return parseFloat(a.xml_channel_frequency) > parseFloat(b.xml_channel_frequency)
        ? 1
        : parseFloat(b.xml_channel_frequency) > parseFloat(a.xml_channel_frequency)
          ? -1
          : 0;
    });
  }
}

function serializeTERChannels(channels) {
  var res = '';
  for (var i = 0; i < channels.length; i++) {
    if (channels[i].xml_signalType != '') {
      res += '<CHANNEL name="' + channels[i].xml_channel_name + '" frequency="' + channels[i].xml_channel_frequency + '" units="MHz" >\n';
      res += '<SIGNAL>\n';
      if (channels[i].xml_channel_stardand_tv == undefined && channels[i].xml_channel_bandwidth == undefined && channels[i].children == undefined) {
        // if((channels[i].children[0].profile == undefined || channels[i].children[0].profile == "") && (channels[i].children[0].layer == undefined || channels[i].children[0].layer == "") &&
        //     (channels[i].children[0].dslice == undefined || channels[i].children[0].dslice == "")){
        if (channels[i].xml_signalType == 'analog') {
          res += '<' + channels[i].xml_signalType.toUpperCase() + 'TER />\n';
        } else {
          res += '<' + channels[i].xml_signalType.toUpperCase() + ' />\n';
        }
        // }
      } else {
        if (channels[i].xml_signalType == 'analog') {
          res += '<' + channels[i].xml_signalType.toUpperCase() + 'TER>\n';
        } else {
          res += '<' + channels[i].xml_signalType.toUpperCase() + '>\n';
        }

        if (channels[i].children != undefined) {
          for (var j = 0; j < channels[i].children.length; j++) {
            if (channels[i].children[j].profile != undefined && channels[i].children[0].profile != '') {
              res += '<PROFILE value="' + channels[i].children[j].profile.toUpperCase() + '">\n';
              if (channels[i].children[j].children.length > 0) {
                for (var k = 0; k < channels[i].children[j].children.length; k++) {
                  res += '<PLP value="' + channels[i].children[j].children[k].xml_plp_value + '" />\n';
                }
              }
              res += '</PROFILE>\n';
            }

            if (channels[i].children[j].dslice != undefined && channels[i].children[0].dslice != '') {
              res += '<DSLICE value="' + channels[i].children[j].dslice + '">\n';
              if (channels[i].children[j].children.length > 0) {
                for (var k = 0; k < channels[i].children[j].children[k]; k++) {
                  res += '<PLP value="' + channels[i].children[j].children[k].xml_plp_value + '" />\n';
                }
              }
              res += '<DSLICE />\n';
            }

            if (channels[i].children[j].layer != undefined && channels[i].children[0].layer != '') {
              res += '<LAYER value="' + channels[i].children[j].layer.toUpperCase() + '" />\n';
            }

            if (channels[i].children[0].xml_channel_symbol_rate != '' && channels[i].children[0].xml_channel_symbol_rate != undefined) {
              res += '<SYMBOLRATE value="' + channels[i].children[0].xml_channel_symbol_rate + '" units="kSymb/s" />\n';
            }
          }
        }

        if (channels[i].xml_channel_stardand_tv != '' && channels[i].xml_channel_stardand_tv != undefined) {
          res += serializeTvSystem(channels[i].xml_channel_stardand_tv);
        }

        if (channels[i].xml_channel_bandwidth != '' && channels[i].xml_channel_bandwidth != undefined) {
          res += '<BANDWIDTH value="' + channels[i].xml_channel_bandwidth + '" units="kHz" />\n';
        }
        if (channels[i].xml_signalType == 'analog') {
          res += '</' + channels[i].xml_signalType.toUpperCase() + 'TER>\n';
        } else {
          res += '</' + channels[i].xml_signalType.toUpperCase() + '>\n';
        }
      }

      res += '</SIGNAL>\n';
      res += '</CHANNEL>\n';
    } else {
      res += '<CHANNEL name="' + channels[i].xml_channel_name + '" frequency="' + channels[i].xml_channel_frequency + '" units="MHz" />\n';
    }
  }
  return res;
}

function serializeSATChannels(channels) {
  var res = '';
  for (var i = 0; i < channels.length; i++) {
    res += '<CHANNEL name="' + channels[i].xml_channel_name + '" downlink="' + channels[i].xml_channel_frequency + '" units="MHz">\n';
    if (channels[i].children[0].xml_channel_band != '' && channels[i].children[0].xml_channel_polarization != '') {
      res +=
        '<SAT band="' +
        channels[i].children[0].xml_channel_band.toUpperCase() +
        '" polarization="' +
        channels[i].children[0].xml_channel_polarization.toUpperCase() +
        '"/>\n';
    }

    if (channels[i].xml_signalType != '') {
      res += '<SIGNAL>\n';
      if (channels[i].xml_channel_bandwidth == undefined && channels[i].children[0].xml_channel_symbol_rate == undefined) {
        if (channels[i].xml_signalType == 'analog') {
          res += '<' + channels[i].xml_signalType.toUpperCase() + 'SAT />\n';
        } else {
          res += '<' + channels[i].xml_signalType.toUpperCase() + '/>\n';
        }
      } else {
        if (channels[i].xml_signalType == 'analog') {
          res += '<' + channels[i].xml_signalType.toUpperCase() + 'SAT />\n';
        } else {
          res += '<' + channels[i].xml_signalType.toUpperCase() + '>\n';
        }
        if (channels[i].children[0].xml_channel_symbol_rate != '' && channels[i].children[0].xml_channel_symbol_rate != undefined) {
          res += '<SYMBOLRATE value="' + channels[i].children[0].xml_channel_symbol_rate + '" units="kSymb/s" />\n';
        }
        if (channels[i].xml_channel_bandwidth != '' && channels[i].xml_channel_bandwidth != undefined) {
          res += '<BANDWIDTH value="' + channels[i].xml_channel_bandwidth + '" units="kHz" />\n';
        }

        if (channels[i].xml_channel_stardand_tv != '' && channels[i].xml_channel_stardand_tv != undefined) {
          res += serializeTvSystem(channels[i].xml_channel_stardand_tv);
        }
        if (channels[i].xml_signalType == 'analog') {
          res += '<' + channels[i].xml_signalType.toUpperCase() + 'SAT />\n';
        } else {
          res += '</' + channels[i].xml_signalType.toUpperCase() + '>\n';
        }
      }

      res += '</SIGNAL>\n';
    } else {
      res += '<SIGNAL />\n';
    }

    if (channels[i].children[0].xml_channel_lnb != '' && channels[i].children[0].xml_channel_lnb != undefined) {
      res += '<LNB>' + channels[i].children[0].xml_channel_lnb + '</LNB>\n';
    }
    res += '</CHANNEL>\n';
  }
  return res;
}

function calcularFrecAnalogica(frecuenciaCentral, bandwidth) {
  return frecuenciaCentral - bandwidth / 2 + 1250000;
}

function calcularFrecCentral(frecuenciaAnalog, bandwidth) {
  return frecuenciaAnalog + bandwidth / 2 - 1250000;
}

function serializeCableRangerChannels(channelplan) {
  var res = '';
  for (var i = 0; i < channelplan.channels.length; i++) {
    res += '<CHANNEL name="' + channelplan.channels[i].xml_channel_name + '" >\n';
    for (var j = 0; j < channelplan.channels[i].children.length; j++) {
      res += '<active type="QString">' + channelplan.channels[i].xml_active + '</active>\n';
      res += '<bandwidth type="double">' + parseFloat(channelplan.channels[i].xml_bandwidth) * 1000000 + '</bandwidth>\n';
      if (channelplan.channels[i].children[j].hasOwnProperty('xml_docsis_group')) {
        res += '<docsisGroup type="double">' + channelplan.channels[i].children[j].xml_docsis_group + '</docsisGroup>\n';
      } else {
        res += '<docsisGroup type="double"></docsisGroup>\n';
      }
      if (isNaN(parseFloat(channelplan.channels[i].children[j].xml_freq_audio))) {
        res += '<freqAudio type="QString">' + channelplan.channels[i].children[j].xml_freq_audio + '</freqAudio>\n';
      } else {
        res += '<freqAudio type="QString">' + parseFloat(channelplan.channels[i].children[j].xml_freq_audio).toFixed(2) + '</freqAudio>\n';
      }

      if (channelplan.channels[i].xml_channel_type == 'ANALOG') {
        var analoglFrequency = parseFloat(channelplan.channels[i].xml_channel_frequency) * 1000000;
        var bandwith = parseFloat(channelplan.channels[i].xml_bandwidth) * 1000000;
        res += '<frequency type="double">' + calcularFrecCentral(analoglFrequency, bandwith) + '</frequency>\n';
      } else {
        res += '<frequency type="double">' + parseFloat(channelplan.channels[i].xml_channel_frequency) * 1000000 + '</frequency>\n';
      }
      res +=
        '<frequencyOffset type="double">' + parseFloat(channelplan.channels[i].children[j].xml_frequency_offset) * 1000000 + '</frequencyOffset>\n';
      res += '<plan type="QString">' + channelplan.xml_name + '</plan>\n';
      res += '<primaryCarrier type="QString">' + channelplan.channels[i].children[j].xml_primary_carrier + '</primaryCarrier>\n';
      res += '<system type="QString">' + channelplan.channels[i].xml_signalType + '</system>\n';
      res += '<type type="QString">' + channelplan.channels[i].xml_channel_type + '</type>\n';
    }
    res += '</CHANNEL>\n';
  }
  return res;
}

function serializeChannels(channelPlan, family_equipment) {
  var res = '';
  if (family_equipment == 'D0') {
    res += '<CHANNELS>\n';
    if (channelPlan.header.xml_band != '') {
      if (channelPlan.xml_band == 'terrestrial') {
        res += serializeTERChannels(channelPlan.channels);
      }
      if (channelPlan.xml_band == 'satellite') {
        res += serializeSATChannels(channelPlan.channels);
      }
    }
    res += '</CHANNELS>\n';
    res += '</CHANNEL-SET>\n';
  } else {
    // res += '<CHANNEL>';
    res += serializeCableRangerChannels(channelPlan);
    // res+= '</CHANNEL>';
    res += '</CHANNEL_PLAN>\n';
  }

  return res;
}

function channelPlan2json_toXml(channelPlan, family_equipment) {
  var date = new Date();
  var formatDate = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();

  var res = '<?xml version="1.0" encoding="utf-8"?>\n';

  if (family_equipment == 'D0') {
    res +=
      '<CHANNEL-SET band="' +
      channelPlan.xml_band.toUpperCase() +
      '" date="' +
      formatDate +
      '" equipment="' +
      channelPlan.xml_equipment +
      '" name="' +
      channelPlan.xml_name +
      '" ' +
      'trademark="' +
      channelPlan.xml_trademark +
      '" version="' +
      channelPlan.xml_version +
      '">\n';

    res += serializeHeader(channelPlan);
    res += serializeExtra(channelPlan);
  } else {
    res +=
      '<CHANNEL_PLAN name="' +
      channelPlan.xml_name +
      '" standard="' +
      channelPlan.xml_standard +
      '" date="' +
      formatDate +
      '" equipment="CABLE RANGER">\n';
  }

  res += serializeChannels(channelPlan, family_equipment);

  return res;
}

function channelPlan2json_toJSON(stringXmlChannelPlan, family_equipment, arrayFileNamesInDirectory) {
  var parser = new DOMParser();
  xmlDoc = parser.parseFromString(stringXmlChannelPlan, 'text/xml');

  if (family_equipment == 'D0') {
    var jsonObj = {
      xml_name: xmlDoc.getElementsByTagName('CHANNEL-SET')[0].getAttribute('name'),
      xml_band: xmlDoc.getElementsByTagName('CHANNEL-SET')[0].getAttribute('band').toLowerCase(),
      xml_equipment: xmlDoc.getElementsByTagName('CHANNEL-SET')[0].getAttribute('equipment'),
      xml_trademark: xmlDoc.getElementsByTagName('CHANNEL-SET')[0].getAttribute('trademark'),
      xml_version: xmlDoc.getElementsByTagName('CHANNEL-SET')[0].getAttribute('version'),
    };

    serializeJSONHeader(jsonObj, xmlDoc);
    serializeJSONChannels(jsonObj, xmlDoc, family_equipment);
  } else {
    var jsonObj = {
      // xml_name: xmlDoc.getElementsByTagName("CHANNEL_PLAN")[0].getAttribute("name"),
      xml_standard: xmlDoc.getElementsByTagName('CHANNEL_PLAN')[0].getAttribute('standard'),
      xml_equipment: xmlDoc.getElementsByTagName('CHANNEL_PLAN')[0].getAttribute('equipment'),
      xml_name: xmlDoc.getElementsByTagName('CHANNEL_PLAN')[0].getAttribute('name'),
    };

    serializeJSONChannels(jsonObj, xmlDoc, family_equipment);
  }

  return jsonObj;
}
